2014-10-12 55 views
0

目前,我有以下各表的東西:實體framwork - 左加入或simalar

AspNetUsers(Id, PasswordHash,....) //standard ASP Identity 2.0 table 
Category(Id, Name) 
CategoryUser(CategoryId, UserId) // link table to turn many-to-many into a one-to-many 

我的班匹配這些實體:

[Table("Category")] 
public class Category 
{ 
    [Key] 
    public Int32? CategoryId { get; set; } 

    public string CategoryName { get; set; } 

    public Int32? Category_ParentID { get; set; } 

    public virtual Category Parent_Category { get; set; } 

    public virtual ICollection<UserCategory> Parent_UserCategories { get; set; } 

    public virtual ICollection<Category> SubCategories { get; set; } 

    public Int16 CategoryOrder { get; set; } 

    public bool Deleted { get; set; } 

} 


[Table("UserCategory")] 
public class UserCategory 
{ 

    [Key] 
    [Column(Order=1)] 
    public Int32 UserId { get; set; } 

    [Key] 
    [Column(Order = 2)] 
    public Int32 CategoryId { get; set; } 

    public virtual Category UsersCategory { get; set; } 

    public virtual ApplicationUser UserCategoryUser { get; set; } 

    public bool CanEditCategory { get; set; } 

    public bool CanDeleteCategory { get; set; } 

    public bool CanViewCategory { get; set; } 

    public bool CanChangePermissions { get; set; } 

} 

該查詢返回被髮送到視圖模型:

 //Retrive the category-if the user has access 
     Password selectedCategory = DatabaseContext.Category.Include("Parent_UserCategories").Where(pass => !pass.Deleted 
              && (
               (DatabaseContext.UserCategories.Any(up => up.CategoryId == pass.CategoryId && up.UserId == UserId)) 
              || (userIsAdmin && ApplicationSettings.Default.AdminsHaveAccessToAllPasswords) 
              || pass.Creator_Id == UserId) 
               ).SingleOrDefault(p => p.CategoryId == 1); 

我想要做的是有一個視圖,它將顯示所有的用戶和他們擁有的訪問權限。我已經有回發的視圖設置...但它只顯示數據庫中已經存在的權限記錄。我需要列出所有用戶(無論他們是否有CategoryUser記錄)以及相應的CategoryUser記錄(如果他們有記錄)。

我有很多想法可以使這項工作,但理想情況下,我想最有效和最乾淨的解決方案 - 我也試圖避免LINQ 2 SQL。

回答

0

那麼,這裏是一個樣例來寫Linq中的左外連接。我給你留下了適應你的問題的負擔:

var joint = from user in context.Users 
      from perm in context.UserPermissions.Where(p=>p.UserId == user.UserId) 
      select new {User=user,Permissions=perm} 

如果用戶和權限共享一對多關係。

var joint = from user in context.Users 
      from perm in context.UserPermissions.SingleOrDefault(p=>p.UserId == user.UserId) 
      select new {User=user,Permission=perm} 

如果用戶和權限共享基數1..0雙方一比一的關係: