【问题标题】:How do I map to a lookup table using Entity Framework Code First with Fluent API如何使用 Entity Framework Code First 和 Fluent API 映射到查找表
【发布时间】:2014-04-19 12:36:27
【问题描述】:

我是 asp.net mvc 和实体框架代码的新手,我对数据库也不是很感兴趣。对于错误的术语或我理解事物的方式,我提前道歉。

现在回答问题。我有以下模型:
用户模型

 public class User
{
    public int UserId { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }

    public int RoleId { get; set; }

    [ForeignKey("RoleId")]
    public virtual IEnumerable<Role> Roles { get; set; }
}

榜样

 public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }       
}

我最终想要的是一种使用 Ef codefirst 方法和流式 API 将 UserId 和 RoleId 映射到具有一对多关系的 User_Role 表的方法,用户可以拥有多个角色:

我认为this question 中的做法是正确的,只是作者使用了多对多连接。我这样尝试过,但是带有 u => u.users 的部分给了我一个错误(我认为那是因为模型中没有 users 属性,所以他回答了他的问题但没有更新他的问题?)

我的问题:让 Ef 为我生成此表的确切 fluent api 代码是什么?

我不确定的事情:(请忽略)

  • 这是解决我的问题的正确方法吗?
  • 一旦我有了查找表,这仍然是声明导航属性的正确方法,以便我以后可以像 user.Roles 一样使用它并检索他们的角色吗?
  • User 模型中的 RoleId 将从何处填充,Roles 表或 User_Role?
  • 在查找表中有 ID 有用吗?

提前致谢!非常感谢您的专业知识。

【问题讨论】:

    标签: database asp.net-mvc-4 ef-code-first fluent


    【解决方案1】:

    首先,您应该删除 User 模型中的 RoleId 属性。将其作为外键告诉用户具有哪个单一角色。由于一个用户可以有多个角色,所以外键不应该在用户表中,而应该在映射表中。

    所以你拥有的是用户和角色之间的多对多关系,Entity Framework 可以自动创建所需的映射表,而无需你进行任何配置。

    如果您只是在User 实体中有一个Roles 属性,在Role 实体中有一个Users 属性,EF 会发现您想要这两者之间的多对多,并创建将两个实体的主键作为组合主键的表,用于将用户映射到角色。

    从数据库中加载User 时,您可以使用Roles 导航属性来确定用户拥有哪些角色,并且您可以加载Role 来确定哪些用户属于该角色。

    使其工作的最简单方法是这样的:

    public class Context : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
    
        static Context()
        {
            Database.SetInitializer(new DropCreateDatabaseAlways<Context>());
        }
    
        public Context()
            : base("Server=localhost;Initial Catalog=Test;Integrated Security=True;")
        {
        }
    }
    
    public class User
    {
        public int UserId { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    
        public List<Role> Roles { get; set; }
    }
    
    public class Role
    {
        public int RoleId { get; set; }
        public string RoleName { get; set; }
    
        public List<User> Users { get; set; }
    }
    

    运行该代码会生成 3 个如下表:

    【讨论】:

    • 非常感谢您帮我解决问题!它现在工作正常。
    • 很好的答案!与OP不匹配的一件事是UserRoles中没有ID字段(参见OP关系图中的User_Role)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 2014-02-07
    相关资源
    最近更新 更多