简体   繁体   中英

Getting non-unique matches with Entity Framework context

I am passing a list of of non-unique longs representing Ids to an entity framework context. With the following code, for every non-unique sub-set of longs in the list which here is IList<long> userIds I get a single User object

context.Users.Where(x =>  UserIds.Contains(x.Id)).ToListAsync();

So passing a list like {1, 1, 1, 2} will return {John, Michael} . The return I want is {John, John, John, Michael} . How can I achieve that?

I think you will have to run a query against the server for each userId in that case:

var matchingUserList = userIds.Select(uid => context.Users.FirstOrDefault(u => u.Id == uid)).ToList();

Interestingly, it appears LINQ doesn't send the duplicate query to the SQL server, it apparently caches the result.

If executing multiple queries against the server might be prohibitive, you could run one query then map to the desired result:

var umap = Users.Where(u => userIds.Distinct().Contains(u.Userid)).ToDictionary(u => u.Userid);
var matchingUserList = userIds.Select(i => umap[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM