简体   繁体   English

如何在EF Core中使用LINQ将原始数据类型列表与实体连接起来?

[英]How to join a list of primitive data type with entity using LINQ in EF Core?

In a .NET Standard 2.0 C# class library project, I am using EF Core . 在.NET Standard 2.0 C#类库项目中,我正在使用EF Core Using LINQ, I want to join a list of integers with a list of users to get the results like follows: 使用LINQ,我想将整数列表与用户列表连接起来,以得到如下结果:

 //List of Ids(can contain 10,000+ entries)
 var lstNums = new List<int>(){1,2,3,4 };

 var lstOutput = (from u in _context.Users
                  join id in lstNums on u.Id equals id 
                  select u).ToList();

This query was working fine in EntityFramwork 6.2 in Database-First approach. 该查询在EntityFramwork 6.2中以数据库优先的方式工作正常。 Recently I migrated to EF Core Code-First and this query stopped working. 最近,我迁移到EF Core Code-First,此查询停止了工作。 I tested with 3 records in lstNums but still it's not working. 我在lstNums测试了3条记录,但仍然无法正常工作。

The Contains() method works fine in this case but the problem is I don't know how entries lstNums will contain. 在这种情况下, Contains()方法可以正常工作,但问题是我不知道lstNums条目将如何包含。 I am not using Contains() since it will exceed the IN clause max-length in some cases. 我没有使用Contains(),因为在某些情况下它将超过IN子句的最大长度。

Any solution to this problem is highly appreciated. 高度赞赏此问题的任何解决方案。

Joins to in-memory collections are not supported well by all EF versions. 并非所有EF版本都支持加入内存中集合。 EF6 supports the for primitive type collection like in your example, while EF Core doesn't. 像您的示例一样,EF6支持for原始类型集合,而EF Core不支持。 This might change in some future version (they are working extensively on query translation, and currently even rewriting it for v3.0). 这可能会在将来的版本中发生变化(他们正在广泛地进行查询翻译,甚至目前针对v3.0进行了重写)。

The safer approach for such type of in-memory collections though is to use Contains instead of join, because it's know to work in all EF versions, eg instead of 对于这种类型的内存集合,更安全的方法是使用Contains而不是join,因为它知道可以在所有EF版本中使用,例如代替

join id in lstNums on u.Id equals id

use 采用

where lstNums.Contains(u.Id)

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

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