如何基于组合主键的集合搜索实体

时间:2019-11-17 07:39:04

标签: c# .net-core ef-core-2.2 ef-core-3.0

我有一个具有复合主键的实体

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) }  
}

1 个答案:

答案 0 :(得分:-1)

context.Products.Where(p => keys.Any( k => k.ProductId == p.ProductId 
                                     &&  k.WarehouseId == p.WarehouseId
                                     && k.Date == p.Date
                                     ) 
                       ) 
                 .ToList();