【发布时间】:2017-12-26 03:24:42
【问题描述】:
我有这个使用 EF db 上下文的测试查询。
Func<Item, ItemDto> qry = x => new ItemDto() {
Id = x.Id,
Name = x.Name
};
List<ItemDto> test1 = db.Items.Select(qry).ToList(); // works
List<ItemDto> test2 = (from item in db.Items select qry).ToList(); // run-time error
我的运行时错误
Cannot implicitly convert type 'System.Collections.Generic.List<System.Func<Progam.Item, Progam.ItemDto>>' to 'System.Collections.Generic.List<Progam.ItemDto>'
首先我不关注错误,而是想知道 Lambda-way Select 和 Linq-way Select Reference to NikolaiDante's answer 之间的区别。
谢谢!
*编辑
假设目标实际上是拥有类似的东西
Func<Item, ItemDto> qry = x => new ItemDto() {
Id = x.Id,
ItemCode = x.ItemCode
};
var qry1 = (from p in db.Sales
select new SaleDto() {
TranNo = p.TranNo
, ExtItem = (from p1 in db.Items.Where(p2 => p2.ProductCode == p.ItemCode)
select qry).FirstOrDefault()
}).ToList();
var qry2 = (from p in db.Returns
select new ReturnDto() {
TranNo = p.TranNo
, ExtItem = (from p1 in db.Items.Where(p2 => p2.ProductCode == p.ItemCode)
select qry).FirstOrDefault()
}).ToList();
这可行吗?我确定我在这里做错了什么,可能有更好的模式来解决这个问题?
注意:我在这里也尝试做的是一次性查询,并避免在查询后使用foreach。
【问题讨论】:
-
不是运行时错误。
select qry->select qry(item) -
@PetSerAl 抱歉,您能进一步解释一下吗?