1

I know it was asked before, but I haven't managed to find up-to-date and complete answer for it.

So, what is the most efficient way to get a list of entities by their primary keys?

We have two separate cases, I guess:

  1. The primary key is simple i.e. over one column For instance, I have IEnumerable<int> ids I want to get all entities where Id of entity is in ids
  2. The primary key is composite i.e. over multiple columns Similar as above but ids is something like IEnumerable<Tuple<int, int, int>>, for instance
DixonD
  • 6,557
  • 5
  • 31
  • 52
  • what do you mean by list by primary keys? if you have the primary key, shouldn't you only be getting one entry? please clarify you question with some code, even if it's hypothetical code. – DLeh Feb 04 '15 at 21:02
  • One entry per each key, of course. Let's say I have a list of ids (non-composite keys) and I want to get a list of entities for them. – DixonD Feb 04 '15 at 21:04
  • add some code to show what you're trying to do, and explain what about it is not working. – DLeh Feb 04 '15 at 21:05
  • If you are using Entity Framework as an ORM (i.e., working with the POCOs, and not directly with the store), it doesn't make a difference whether the compared values in the predicate for the query are primary keys or not (that will make a difference in the store call, but not on EF), and wouldn't make a difference if they are composite or not. – Jcl Feb 04 '15 at 21:07
  • @Jcl Well, I think, there is a difference if you want to query by one column or by multiple columns - in the former case you can use Contains which should be translated in the IN clause by EF. – DixonD Feb 04 '15 at 21:21
  • Are you trying to find a single way to query that works for both cases? Or are you asking how to do each case separately? – Steven U Feb 04 '15 at 23:54
  • @StevenU Either way, but I guess each case should be handled separately for better performance – DixonD Feb 04 '15 at 23:56
  • Are you using a strongly typed DbContext? – Steven U Feb 05 '15 at 00:07
  • @DixonD of course... what I meant was: there's no difference in EF terms from checking a composite primary key or "n-other-whatever-fields-that-are-not-primary-key". The difference is not whether they are primary key or not. As I said: that might mean a difference for the store -SQL Server or whatnot-, but not for EF if you are using the context's POCO collections (unless that involves joins, but you don't specify that) – Jcl Feb 05 '15 at 06:16
  • @Jcl Yes, I've got your point. I guess, I shouldn't have mentioned querying on primary keys, but rather on any columns. – DixonD Feb 05 '15 at 06:53

0 Answers0