问题描述
我正在使用 C# 和 .NET Framework 4.5.1 从带有 Entity Framework 6.1.3 的 SQL Server 数据库中检索数据.
I'm working with C# and .NET Framework 4.5.1 retrieving data from a SQL Server database with Entity Framework 6.1.3.
我有这个:
codes = codesRepo.SearchFor(predicate)
.Select(c => new Tuple<string, byte>(c.Id, c.Flag))
.ToList();
当我运行它时,我会收到以下消息:
And when I run it, I get this message:
LINQ 仅支持无参数构造函数和初始化程序到实体.
Only parameterless constructors and initializers are supported in LINQ to Entities.
我不知道我必须如何创建元组,因为我找到的所有示例大多都是这样的.
I don't know how I have to create the Tuple because all the examples that I have found are mostly like this one.
我试过这个:
codes = codesRepo.SearchFor(predicate)
.Select(c => Tuple.Create(c.Id, c.Flag))
.ToList();
并得到这个错误:
LINQ to Entities 无法识别该方法'System.Tuple`2[System.String,System.Byte]Create[String,Byte](System.String, Byte)' 方法,以及这个方法无法翻译成商店表达式.
LINQ to Entities does not recognize the method 'System.Tuple`2[System.String,System.Byte] Create[String,Byte](System.String, Byte)' method, and this method cannot be translated into a store expression.
问题出在哪里?
推荐答案
虽然 answer by octavioccl 有效,最好先将查询结果投影为匿名类型,然后切换到可枚举并将其转换为元组.这样,您的查询将只从数据库中检索所需的字段.
While the answer by octavioccl works, it's better to first project the query result into anonymous type, and then switch to enumerable and convert it to tuple. This way your query will retrieve from the data base only the fields needed.
codes = codesRepo.SearchFor(predicate)
.Select(c => new { c.Id, c.Flag })
.AsEnumerable()
.Select(c => new Tuple<string, byte>(c.Id, c.Flag))
.ToList();
<小时>
注意:以上规则适用于 EF6.EF Core 通过元组构造函数自然地支持元组(在投影中或作为连接/组键),例如原始查询很有效
Note: The above rule applies to EF6. EF Core naturally supports tuples (in projection or as join/group keys) via tuple constructor, e.g. the original query simply works
codes = codesRepo.SearchFor(predicate)
.Select(c => new Tuple<string, byte>(c.Id, c.Flag))
.ToList();
但不是 Tuple.Create
方法 (EF Core 2.x).
but not the Tuple.Create
method (EF Core 2.x).
这篇关于在 Linq Select 中创建元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!