Entity Framework 6如何進行導航屬性的篩選(context.Msg.First(t=>t.Id==1).Include(t=>t.MsgDetail),篩選MsgDetail帶條件)
問題: https://q.cnblogs.com/q/98333/
Msg表(Id,Content,IsDel)。內有 virtual ICollection<MsgDetail> MsgDetails屬性
MsgDetail表(Id,MsgId,SubContent,IsDel)
兩者是一對多關系。
如何進行如下意思的的篩選?
若寫這句偽代碼:
context.Msg.First(t=>t.Id==1).Include(t=>t.MsgDetail.Where(t=>t.IsDel == false)) //僅篩選IsDel==false的MsgDetails記錄。
其中Include(t=>t.MsgDetail.Where(t=>t.IsDel == false)) 將報錯
只能.Include(t=>t.MsgDetail) 後再次linq to object篩選
解決:
下面以Blog~Comments 的一對多關系為例解釋、書寫代碼。
db.Configuration.LazyLoadingEnabled = false; //必須關閉延遲加載,否則一旦使用Blog.Comments就會再次查詢DB的Comments表,加載Blog下的所以Comments而不篩選IsDel。
Blog blog = db.Blog.Include(b => b.Comments)
.Select(b => new {BlogEntity = b, Comments = b.Comments.Where(c => c.IsDel == false)})
.Where(blogEntity => blogEntity.BlogEntity.Id == id)
.ToList() //立即執行sql查詢
.Select(t => t.BlogEntity).First(); //linq to object內存查詢、ef自動轉換Comments到BlogEntity.Comments
//方法2
//var ret = db.Blog.Include(b => b.Comments)
// .Select(b => new {BlogEntity = b, Comments = b.Comments.Where(c => c.IsDel == false)})
// .FirstOrDefault(blogEntity => blogEntity.BlogEntity.Id == id); //FirstOrDefault
//Blog blog = ret == null ? null : ret.BlogEntity;
參考:http://www.bkjia.com/Asp_Netjc/970649.html
http://stackoverflow.com/questions/25276978/ef-6-add-where-clause-to-an-include-with-navigation-property
Entity Framework 6如何進行導航屬性的篩選(context.Msg.First(t=>t.Id==1).Include(t=>t.MsgDetail),篩選MsgDetail)
0 [待解決問題] 瀏覽: 16次Msg表(Id,Content,IsDel)。內有 virtual ICollection<MsgDetail> MsgDetails屬性
MsgDetail表(Id,MsgId,SubContent,IsDel)
兩者是一對多關系。
如何進行如下意思的的篩選?
context.Msg.First(t=>t.Id==1).Include(t=>t.MsgDetail.Where(t=>t.IsDel == false)) //僅篩選IsDel==false的MsgDetails記錄。
上述代碼 : .Include(t=>t.MsgDetail.Where(t=>t.IsDel == false)) 錯誤
只能.Include(t=>t.MsgDetail.Where(t=>t.IsDel == false)
何解?
Entity Framework 6如何進行導航屬性的篩選(context.Msg.First(t=>t.Id==1).Include(t=>t.MsgDetail),篩選MsgDetail帶條件)