【问题标题】:Object mapping in code-first, cannot get table property代码优先的对象映射,无法获取表属性
【发布时间】:2015-12-22 20:45:34
【问题描述】:

我首先学习代码并尝试为我的项目创建数据库模型。为了让我的问题简单,我将在我的模型中使用两个表 - 用户和角色

我现在的主要问题是我无法通过使用 property 获得 role。例如我的代码:

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

返回空值。我认为这是模型映射的问题。我的用户类看起来像:

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

我的角色类:

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

这两个类的数据库上下文:

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

    }

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

你能帮我做模型映射吗? 谢谢大家的回答!

【问题讨论】:

    标签: c# .net asp.net-mvc entity-framework-5 code-first


    【解决方案1】:

    您应该在查询中包含角色,如下所示:

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

    您也可以使用.Include(u =&gt; u.Role) 代替.Include("Role"),这更好,但不适用于MySql 数据库和某些特定控制器。

    您还应该在 User 类中将 Role 属性声明为虚拟:

      public virtual Role Role { get; set; }
    

    【讨论】:

    • 此代码在我的项目中仍然返回空角色,我无法添加:.Include(u => u.Role)
    • 是的,我现在检查了我的代码:var role = dbContext.Users.Include("Role").First(n => n.UserId == currentUser.UserId).Role;跨度>
    • 我的角色属性中需要一个虚拟角色,并且我在我的用户类构造函数中创建了一个新角色,所以每次我为我的用户获得一个新角色时。感谢您的帮助
    猜你喜欢
    • 2012-01-09
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多