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

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

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,new { WarehouseId = warehouse2.Id,Date = 13.January(2020) },Date = 13.January(2020) }  
}
jyc2410 回答:如何基于组合主键的集合搜索实体

context.Products.Where(p => keys.Any( k => k.ProductId == p.ProductId 
                                     &&  k.WarehouseId == p.WarehouseId
                                     && k.Date == p.Date
                                     ) 
                       ) 
                 .ToList();
本文链接:https://www.f2er.com/3087299.html

大家都在问