我一直在几个项目中使用 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/