[英]How to Explicit loading specific related entities for specific entities using Entity Framework?
我有兩個數據庫表:
1) 位置 ,其具有許多職員
2)具有多種作用的員工
如果我只想加載在特定位置具有主管角色的相關人員,我會這樣做:
var location = dbContext.Locations.Find(locationId);
dbContext.Entry(location).Collection(b => b.Staffs).Query().Where(s => s.Roles.Any(r => r.Name=="Supervisor"));
我的問題是如何為所有位置具有主管角色的相關員工實現明確的工作量(我不需要上述特定人員)?
您可以使用SelectMany展平所有位置的“員工”列表。 然后您可以根據角色進行過濾
dbContext.Locations.SelectMany(b => b.Staffs).Where(s => s.Roles.Any(r => r.Name=="Supervisor"));
您可以在SelectMany中返回一個匿名類型,其中將包含Location屬性,例如:
dbContext.Locations.SelectMany(x => x.Staffs, (x, Staffs) =>
new { locationID = x.LocationID, SomeOtherProperty = x.OtherProperty , Staff = Staffs })
.Where(y => y.Staff.Roles.Any(z => z.Name == "Supervisor"));
我對存儲庫模式的實現做了類似的操作。 關鍵是最后調用Load
。
我們有
public virtual void Load<TOut>(T entity, Expression<Func<T, ICollection<TOut>>> loadExpression, Expression<Func<TOut, bool>> filter) where TOut : class
{
Context.Entry(entity).Collection(loadExpression).Query().Where(filter).Load();
}
因此,對於您的情況,您可以嘗試
dbContext.Entry(location).Collection(b => b.Staffs).Query()
.Where(s => s.Roles.Any(r => r.Name=="Supervisor")).Load();
然后遍歷所有位置並加載引用。 另一個選擇是為您的案例編寫一個顯式的Linq2Entities
查詢。
var locationWithStaff = (from location in dbContext.Locations
select new
{
location,
Staffs = (from staff in location.Staffs
where staff.Roles.Any(r => r.Name=="Supervisor")
select staff).ToList()
}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.