2014-01-22 44 views
0

我有以下實體:如何寫,留下了衆多加盟一對多的關係

實體:系 DepartmentID的(INT) 名稱(INT) SuperiorDepartmentId(INT,外鍵部門實體) DepartmentPermissions (ICollection的)

實體:DepartmentPermission DepartmentID的(INT) 用戶ID(INT) 權限(字符串) 部門(ICollection的)

實體:用戶 用戶ID(INT) 名稱(字符串) DepartmentPermissions(ICollection的)

我需要在我的查詢返回所有部門(包括那些在用戶沒有權限)和當用戶有任何權限時的權限名稱。

 
DepartmentId | Name | SuperiorDepartmentId 
1 | Sales | null 
2 | Internal Sales | 1 
3 | Marketing | null 

DepartmentPermissions

 
DepartmentId | User Id | Permission 
1 | 2 | r 
2 | 2 | rw 
1 | 3 | rw 

用戶

 
UserId | Name 
1 | John 
2 | Mary 
3 | Paul 

如果我索要數據對於用戶Mary(id = 2),我們應該有結果集:

 
DepartmentId | Name | SuperiorDepartmentId | Permission 
1 | Sales | null | r 
2 | Internal Sales | 1 | rw 
3 | Marketing | null | null 

我該怎麼做?

回答

0

我打算假定存在導航屬性Department.DepartmentPermissions

var query = from d in context.Departments 
      select new { 
         Department = d, 
         Permissions = d.DepartmentPermissions 
             .Where(dp => dp.UserId == 2) 
             .Select(p => p.Permission) 
         }; 

var result = query.AsEnumerable() 
        .Select(x => 
        new { 
         x.Department.DepartmentId, 
         x.Department.Name, 
         x.Department.SuperiorDepartmentId, 
         Permissions = 
          string.Join(", ", x.Permissions.DefaultIfEmpty("null") 
         } 

首先收集原始數據(query),然後將最終結果組成內存。後者完成是因爲EF在LINQ查詢中不允許string.Join。您的數據結構允許一個部門中的每個用戶擁有多個權限,因此可以是string.Join

如果你絕對相信總會有一個許可,您可以在query

Permission = d.DepartmentPermissions.Where(dp => dp.UserId == 2) 
       .Select(p => p.Permission) 
       .FirstOrDefault() 

,和你做。