Create a Tuple in a Linq Select(在 Linq Select 中创建元组)
问题描述
我正在使用 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 中创建元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Linq Select 中创建元组
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
