我正在尝试使用LINQ Lambda链接许多表,但在处理子查询以获取ProducedBy属性的值时遇到问题。我收到一条消息:对具体化的查询结果消息不支持此方法。
可以帮我一把吗?
var temp = db.MK_Product_Variant
.Join(db.MK_Products, a => a.ProductId, b => b.ID, (a, b) => new { a, b })
.Join(db.MK_Product_Category, c => c.b.CategoryId, d => d.ID, (c, d) => new { c, d })
.Join(db.MK_Game_Type, e => e.d.GameType, f => f.ID, (e, f) => new { e, f })
.Where(g=> !db.MK_MP_Variant.Select(h=>h.ID).Contains( g.e.c.a.ID)) /* My Store only */
.Select(i => new {
Category = i.e.d.Name,
ItemType = i.f.Name,
ItemNo = i.e.c.a.ID,
Enabled = i.e.c.b.Enabled,
Status = "",
ProducedBy = (db.MK_Products.Join(db.MK_Production_Resource,k=>k.ID,l=>l.Item,(k,l) => new {k,l})
.Join(db.MK_Production_Staff,m=>m.l.Staff,n=>n.ID,(m,n) => new {m,n})
.Where(o => o.m.k.ID == i.e.c.a.ID)
.Select(p=>p.n.Location).DefaultIfEmpty("").ToList())[0],
ReleaseDate = i.e.c.a.ReleaseDate,
ReleasingQty = i.e.c.a.Qty,
Price = i.e.c.a.Price_MKD,
QtyPurchaseFromUser = "",
QtySold = db.MK_Product_VariantHistory.Where(j => j.Variant == i.e.c.a.ID && j.PurchaseDate >= startDate && j.PurchaseDate <= stopDate && !(db.MK_MP_Variant.Select(t => t.ID)).Contains(i.e.c.a.ID)).Count()
});
这是我想要使用它的代码行:
int count = 0;
foreach (var item in temp)
{
result.Add(count, new string[] { item.Category, item.ItemType, item.ItemNo.ToString(), item.Enabled.ToString(), "", item.ProducedBy.Count()==0?"":item.ProducedBy.FirstOrDefault().Country , string.Format("{0:yyyy-MM-dd hh:mm:ss tt}", item.ReleaseDate), "", "", item.ReleasingQty.ToString(), "", item.QtySold.ToString(), item.QtyPurchaseFromUser.ToString(), string.Format("{0:#0}", item.Price), "", "", "", "", "" });
count++;
}
答案 0 :(得分:1)
在select
语句之后你有where
,你在select
语句中返回一个匿名类型,它有一个名为ProducedBy
的属性,来设置你写的这个属性查询,最后,调用ToList
来获取第一个元素...
你需要使用FirstOrDefault
代替ToList()
并获得零索引元素:
ProducedBy = db.MK_Products
.Join(db.MK_Production_Resource,k=>k.ID,l=>l.Item,(k,l) => new {k,l})
.Join(db.MK_Production_Staff,m=>m.l.Staff,n=>n.ID,(m,n) => new {m,n})
.Where(o => o.m.k.ID == i.e.c.a.ID)
.Select(p=>p.n.Location)
.DefaultIfEmpty("")
.FirstOrDefault()
你不能在linq到实体之间调用ToList
,除非你的日期被提取到内存之前,如果你想在主要细节情况下在linq到实体中填充一个列表,你可以使用AsEnumerable
代替