I have an entity which has composite primary key
public class Allocation
{
public Guid WarehouseId { get; set; }
public Guid ProductId { get; set; }
public DateTime Date { get; set; }
public int? Quantity { get; set; }
}
Entity configuration
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);
}
}
I can search for one entity by using Find
method which accepts multiple arguments as primary key
var allocation = context.Allocations.Find(warehouseId, productId, date);
For entity with one value for primary key I can search for multiple entities based on collection of primary keys by using givenkeys.Contains()
var keys = new[] { 1, 2, 3, 4 };
var entities = context.Products.Where(product => keys.Contains(product.Id)).ToList();
How I can search for multiple entities based on multiple composite keys?
// 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) }
}