在Linq Select中创建元组 [英] Create a Tuple in a Linq Select

查看:130
本文介绍了在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.

问题出在哪里?

推荐答案

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中创建元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆