简体   繁体   English

使用Entity Framework上下文获取非唯一匹配

[英]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. 我正在将代表ID的非唯一long列表传递给实体框架上下文。 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 使用以下代码,对于列表中每个非唯一的long子集(这里是IList<long> userIds我得到一个User对象

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

So passing a list like {1, 1, 1, 2} will return {John, Michael} . 因此,传递类似{1, 1, 1, 2}将返回{John, Michael} The return I want is {John, John, John, Michael} . 我想要的回报是{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: 我认为在这种情况下,您将必须针对每个userId对服务器运行查询:

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. 有趣的是,看起来LINQ不会将重复查询发送到SQL服务器,它显然是缓存了结果。

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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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