繁体   English   中英

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

[英]Getting non-unique matches with Entity Framework context

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

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

因此,传递类似{1, 1, 1, 2}将返回{John, Michael} 我想要的回报是{John, John, John, Michael} 我该如何实现?

我认为在这种情况下,您将必须针对每个userId对服务器运行查询:

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

有趣的是,看起来LINQ不会将重复查询发送到SQL服务器,它显然是缓存了结果。

如果对服务器执行多个查询可能被禁止,则可以运行一个查询,然后映射到所需的结果:

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