c# - Entity Framework ,如何投影到列表中

标签 c# .net linq entity-framework

我一直在几个项目中使用 linq2sql,但我决定是时候试用 EF 了,因为它应该更强大、更好。有几件事真的很烦人。 其中之一是将结果投影到列表中,这在 l2sql 中运行良好,但在 EF 中则不然。

public class bo.Transaction
{
  public long Id { get; set; }
  public List<bo.Line> Lines { get; set; }
}

public class bo.Line
{
  public int RowNo { get; set; }
  public string Descripton{ get; set; }
  public double Amount{ get; set; }
}

return from t in Db.Transaction.Include("Lines")
       select new bo.Transaction {
         Id = t.Id,
         Lines = t.Lines.OrderBy(l => l.RowNo).ToList(),
       };

然而,ToList() 调用失败,并显示消息“System.NotSupportedException:LINQ to Entities 无法识别方法‘List[bo.Line] ToListLine’方法,并且此方法无法转换为存储表达..”。

有什么办法可以解决这个问题?或者我只需要使用 ienumerable 而不是列表?

最佳答案

return (from t in Db.Transaction.Include("Lines")
       select new bo.Transaction {
         Id = t.Id,
         Lines = t.Lines.OrderBy(l => l.RowNo),
       }).ToList();

Linq 查询不支持列表,所以我们在枚举结果上执行它。不过,它确实会强制查询在那一刻执行。返回 IEnumerable 会稍微延迟查询的执行。 (基本上直到您要访问数据的那一刻。)

关于c# - Entity Framework ,如何投影到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1453381/

相关文章:

.net - .NET 4.5 中的默认安全协议(protocol)

c# - WinForms TabControl拖放问题

c# - LinQ to SQL 忽略 != 虚拟属性上的 null

c# - 找不到 WIX 模板项目

c# - 字符串格式() : multiline string without using plus

c# - 我将如何混淆客户端上的密码并在服务器上进行反混淆

linq - 如何使用LINQ创建嵌套的分组字典?

c# - Volatile.Write新鲜度保证

c# - ElasticSearch:如何在集合中搜索

c# - 转换为值类型 'System.Int32' 失败,因为具体化值为空。