EntityFramework - contains query of composite key

前端 未结 7 1492
渐次进展
渐次进展 2020-11-22 06:06

given a list of ids, I can query all relevant rows by:

context.Table.Where(q => listOfIds.Contains(q.Id));

But how do you achieve the sa

7条回答
  •  伪装坚强ぢ
    2020-11-22 06:55

    You need a set of objects representing the keys you want to query.

    class Key
    {
        int Id1 {get;set;}
        int Id2 {get;set;}
    

    If you have two lists and you simply check that each value appears in their respective list then you are getting the cartesian product of the lists - which is likely not what you want. Instead you need to query the specific combinations required

    List keys = // get keys;
    
    context.Table.Where(q => keys.Any(k => k.Id1 == q.Id1 && k.Id2 == q.Id2)); 
    

    I'm not completely sure that this is valid use of Entity Framework; you may have issues with sending the Key type to the database. If that happens then you can be creative:

    var composites = keys.Select(k => p1 * k.Id1 + p2 * k.Id2).ToList();
    context.Table.Where(q => composites.Contains(p1 * q.Id1 + p2 * q.Id2)); 
    

    You can create an isomorphic function (prime numbers are good for this), something like a hashcode, which you can use to compare the pair of values. As long as the multiplicative factors are co-prime this pattern will be isomorphic (one-to-one) - i.e. the result of p1*Id1 + p2*Id2 will uniquely identify the values of Id1 and Id2 as long as the prime numbers are correctly chosen.

    But then you end up in a situation where you're implementing complex concepts and someone is going to have to support this. Probably better to write a stored procedure which takes the valid key objects.

提交回复
热议问题