实体框架 - 左连接或类似的东西

时间:2014-10-12 11:13:37

标签: c# asp.net-mvc linq entity-framework

我目前有以下表格:

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);

我想要做的是有一个视图,它将显示所有用户及其拥有的访问权限。我已经使用post back进行了视图设置...但它只显示数据库中已存在的权限记录。我需要列出所有用户(无论他们是否有CategoryUser记录),以及相应的CategoryUser记录 - 如果他们有一个。

我有很多想法可以完成这项工作,但理想情况下,我希望能够提供最有效,最干净的解决方案 - 我也试图避免使用LINQ 2 SQL。

1 个答案:

答案 0 :(得分: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共享一对一的关系: