MVC 5,查询对象关系

时间:2016-05-27 06:27:34

标签: asp.net-mvc asp.net-mvc-5 linq-to-entities entity-framework-6

我有User类,UserGroup类和用户上下文:

public class User
{
    [Key]       
    public string UserID { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }      
    public string GroupCode { get; set; }
    public UserStatus Status { get; set; }
    public string Roles { get; set; }

    [ForeignKey("GroupCode")]
    [ConcurrencyCheck]
    public virtual UserGroup UserGroup { get; set; }
}

public class UserGroup
{
    public UserGroup()
    {
        Users = new List<User>();
    }

    [Key]
    [DisplayName("Group Code"), Column("GroupCode", TypeName = "varchar")]
    [MaxLength(20, ErrorMessage = "Group Code maximum length is {0}")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "{0} is required")]
    public string GroupCode { get; set; }

    [DisplayName("Group Name")]
    [MaxLength(20, ErrorMessage = "Group Code maximum length is {0}")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "{0} is required")]
    public string GroupName { get; set; }

    public virtual List<User> Users { get; set; }
}

public class UserDBContext : DbContext
{
    public UserDBContext() : base("SSSS")
    {       
    }

    public DbSet<User> Users { get; set; }
    public DbSet<UserGroup> UserGroups { get; set; }
}

是否可以使用组对象查询用户? 我试试

User user2 = db.Users.Where(u => u.UserID == id)
                .Include(x => x.UserGroup)
                .Include(x1 => x1.UserGroup.Users)
                .FirstOrDefault();

但User对象中的UserGroup对象属性为null。 我需要的是属性非null并且基于User GroupCode键来查找用户的组。

1 个答案:

答案 0 :(得分:1)

试试这个:

User user2 = db.Users
    .Include(x => x.UserGroup)
    .Include(x1 => x1.UserGroup.Select(y => y.Users))
    .Where(u => u.UserID == id)
    .FirstOrDefault();