Search code examples
c#.netasp.net-mvcentity-framework-5code-first

Object mapping in code-first, cannot get table property


Im learning code-first and im trying to create a database model for my project. To make my question simple i will use in my model two tables - user and role

Database diagram in SQL Server

My main problem right now is that i cannot get role by using property. For example my code :

var role = dbContext.Users.FirstOrDefault(n => n.UserId== id).Role;

return null. I think it is problem with model mapping. My User class looks like :

 public class User
    {
        public User()
        {
            Role = new Role();
        }
        public int UserId { get; set; }
        [Required]
        public string Login { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        public string Password { get; set; }
        public DateTime CreationDate { get; set; }

        public DateTime LastLoginDate { get; set; }

        [ForeignKey("Role")]
        public int RoleId { get; set; }

        public Role Role { get; set; }

        public virtual ICollection<Telephone> Telephones { get; set; }
    }

My Role class :

 public class Role
    {
        public Role()
        {
            Users = new List<User>();
        }
        public int RoleId { get; set; }
        public string RoleName { get; set; }
        public string RoleDescription { get; set; }

        public ICollection<User> Users { get; set; }
    }

And db context with these two classes :

public CallCenterContext() : base(@"CONNECTIONSTRING")
    {

    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }

Could you pleas help me with model mapping? Thanks for everyone answer!


Solution

  • You should include the role in your query, like this:

    var role = dbContext.Users
             .Include("Role") // <----- add this
             .FirstOrDefault(n => n.UserId== id).Role;
    

    You can also use .Include(u => u.Role) instead of .Include("Role") which is better but doesn't work with MySql database and some specific controller.

    Also you should declare the Role property as virtual in User class:

      public virtual Role Role { get; set; }