Querying a list of objects with compound keys in EF

I have a table with a composite key, for example:

modelBuilder.Entity<MyEntity>().HasKey(e=> new { e.Part1, e.Part2 });

I also have a list of keys in memory for which I want to load objects, for example:

var keys = new [] { new { Part1= 1, Part2 = 2}, new { Part1= 3, Part2 = 4} }

How can I execute one request to load objects in an array of keys?

I tried obvious things like ctx.MyEntities.Where(e => keys.Any(k => k.Part1 == e.Part1 && k.Part2 == e.Part2))

This answer suggests that this is not possible, but certainly not so.

+4
source share
1 answer

I would recommend doing something like the following:

var part1Keys = keys.Select(k => k.Part1);
var part2Keys = keys.Select(k => k.Part2);

var entities = ctx.MyEntities.Where(e => part1Keys.Contains(e.Part1) && part2Keys.Contains(e.Part2));
-1
source

Source: https://habr.com/ru/post/1568043/


All Articles