【发布时间】:2019-11-17 07:39:04
【问题描述】:
我有一个具有复合主键的实体
public class Allocation
{
public Guid WarehouseId { get; set; }
public Guid ProductId { get; set; }
public DateTime Date { get; set; }
public int? Quantity { get; set; }
}
实体配置
public class AllocationConfiguration : IEntityTypeConfiguration<Allocation>
{
public void Configure(EntityTypeBuilder<Allocation> builder)
{
builder.HasKey(e => new { e.WarehouseId, e.ProductId, e.Date }); // Primary key
builder.Property(e => e.Date).HasColumnType("date");
builder.HasOne<Warehouse>().WithMany().HasForeignKey(e => e.WarehouseId);
builder.HasOne<Product>().WithMany().HasForeignKey(e => e.ProductId);
}
}
我可以使用Find 方法搜索一个实体,该方法接受多个参数作为主键
var allocation = context.Allocations.Find(warehouseId, productId, date);
对于具有一个主键值的实体,我可以使用givenkeys.Contains()基于主键集合搜索多个实体
var keys = new[] { 1, 2, 3, 4 };
var entities = context.Products.Where(product => keys.Contains(product.Id)).ToList();
如何根据多个复合键搜索多个实体?
// Given keys
var keys = new[]
{
new { WarehouseId = warehouse1.Id, ProductId = product1.Id, Date = 12.January(2020) },
new { WarehouseId = warehouse1.Id, ProductId = product2.Id, Date = 12.January(2020) },
new { WarehouseId = warehouse2.Id, ProductId = product1.Id, Date = 13.January(2020) },
new { WarehouseId = warehouse2.Id, ProductId = product2.Id, Date = 13.January(2020) }
}
【问题讨论】:
标签: c# .net-core ef-core-2.2 ef-core-3.0