[英]Eager loading not working in EF 6
我有一種方法可以向我返回員工列表。
public Employee GetAdminTypeAndPermission(int userID)
{
using (var unitOfWork = new EFUnitOfWork())
{
var employeeRepo =
new EmployeeRepository(new EFRepository<Employee>(), unitOfWork);
DbSet<Employee> employeeObjSet =
((EmployeeEntities)employeeRepo.Repository.UnitOfWork.Context).Employees;
return employeeObjSet.Where(emp => emp.FK_UserID == userID).
Include("AdminType.Permissions").FirstOrDefault();
}
}
我正在嘗試使用另一種方法,例如
var employee= GetAdminTypeAndPermission(loginInfo.UserID);
var permission = employee.AdminType.Permissions.FirstOrDefault();
我在以下行出現錯誤:
var permission = employee.AdminType.Permissions.FirstOrDefault();
ObjectContext實例已被處置,不能再用於需要連接的操作。 我了解Context對象在使用完塊之后處理,但是我正在使用Eager加載來訪問Navigation屬性,因此我應該得到結果集。
請幫助我了解我在這里犯了什么錯誤以及如何糾正。
非常感謝您的幫助。 提前致謝。
您在using語句中擁有DbContext:
using (var unitOfWork = new EFUnitOfWork())
一旦您擺脫了using語句,您與數據庫的連接就會有效關閉。 要么:
將DbContext傳遞給方法,以便您可以繼續使用它:
using (var unitOfWork = new EFUnitOfWork()) { var employee= GetAdminTypeAndPermission(loginInfo.UserID, unitOfWork); //DbContext passed in var permission = employee.AdminType.Permissions.FirstOrDefault(); }
好吧,也許您弄錯了相關的表名? 我的意思是, 字符串類型的內容很難在您的代碼中進行控制,也就是說,它是否可能(沒有最后一個“ s”的權限?):
return employeeObjSet.Where(emp => emp.FK_UserID == userID).
Include("AdminType.Permission").FirstOrDefault();
對於這種錯誤,我建議您使用lambda擴展屬性名稱解析程序,即,如果您輸入以下using指令,則將包含Include方法的重載/擴展:
using System.Data.Entity;
這是我傾向於使用的擴展名:
public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path);
它的用法如下:
return employeeObjSet.Where(emp => emp.FK_UserID == userID).
Include(x => x.Permissions).FirstOrDefault();
這里的x.Permission 是因為外匯基金產生的ICollection的多元化,或者你的CF編碼您使用標准。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.