2010-01-11 51 views
1

我有三個相關實體,由該圖最好地描述:協會性質不裝載在實體

alt text http://thehashtable.com/wp-content/uploads/2010/01/Enttities.png

當我加載用戶,使用下面的代碼,所述User對象被加載,即不爲空,但User對象上的RoleDepartment屬性爲空,儘管用戶數據庫記錄具有這些關聯的有效FK值。

using (var productionEntities = new ProductionEntities()) 
{ 
    var userName = GetUserName(); 
    User u = (from usr in productionEntities.UserSet 
       where usr.UserName == userName 
       select usr).FirstOrDefault(); 
    if (u == null) 
    { 
     throw new KpiSecurityException("No local database entry found for user.") { UserName = userName }; 
    } 
    return u.Department.DeptName; 
} 

題外話:我通過這整個任務就只是因爲ASP.NET的MembershipProvider不支持用戶的元數據「像部,我將不得不使用ProfileProvider爲好,成本巨大的數據庫膨脹。

回答

1

既然你只需要該部門的名稱,只是project了這一點;這樣你只能查詢一次數據庫:

using (var productionEntities = new ProductionEntities()) 
{ 
    var userName = GetUserName(); 
    var u = (from usr in productionEntities.UserSet 
       where usr.UserName == userName 
       select new 
       { 
        DeptName = usr.Department.DeptName 
       }).FirstOrDefault(); 
    if (u == null) 
    { 
     throw new KpiSecurityException("No local database entry found for user.") { UserName = userName }; 
    } 
    return u.DeptName; 
} 
3

你必須明確你的查詢加載此特性

User u = (from usr in productionEntities.UserSet 
      where usr.UserName == userName 
      select usr).FirstOrDefault(); 

if (u == null) 
{ 
     throw new KpiSecurityException("No local database entry found for user.") { UserName = userName }; 
} 

if (!u.RoleReference.IsLoaded) 
{ u.RoleReference.Load(); } 

if (!u.DeparmentReference.IsLoaded) 
{ u.DeparmentReference.Load(); } 

或包含此實體

User u = (from usr in productionEntities.UserSet.Include("Role").Include("Department") 
      where usr.UserName == userName 
      select usr).FirstOrDefault(); 
+1

這將導致三個數據庫查詢;只需要一個。 – 2010-01-11 13:40:29

+0

如果您使用「包含」,EF會生成一個查詢。 – 2010-01-12 07:32:36

+0

+1用於教會我IsLoaded和Load()成員。我知道有這樣的事情,但我只是不知道在哪裏尋找它。 – ProfK 2010-01-12 11:40:34