c# - Entity Framework 中的多对多关系有效

标签 c# entity-framework

我正在使用 C# 和 Entity Framework 构建授权应用程序。我有用户、角色、权限、声明表。由于用户和角色具有多对多关系,因此我创建了 use-Role 表。我对映射关系有疑问。

这是我的用户类:

 public class User
     {

    public int UserId { get; set; }

    public string UserName { get; set; }
}

这是我的角色类:

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

    public string RoleName { get; set; }
}

我不确定我应该在 User-Role 类中包含什么才能使多对多关系正常工作,特别是在我进行更新时。
这是我的用户角色类:

 public class UserRole
    {

    public UserRole()
    {
        Roles = new Collection<Role>();
        Users = new Collection<User>();
    }

    public int Id { get; set; }

    public int UserId { get; set; }

    public string UserName { get; set; }

    public int RoleId { get; set; }

    public string RoleName { get; set; }

}

映射应该是什么样子的?

最佳答案

在为您提供解决方案之前,首先要知道您正在重新发明轮子。我这么说是因为ASP.Net Identity只做你想做的事。

无论如何,一些澄清:

  • UserRoleUser之间的关联实体和 Role
  • UserRole需要 Role
  • UserRole需要 User

UserRole表示一个 User 之间的组合和一个Role .您可以有很多这样的实例,就像 User 一样。有很多Role .这就是为什么在用 Fluent API 翻译它之前你必须删除 RolesUsers您放入 UserRole 中的集合并改为创建 UserRoles作为一个集合ICollection<UserRole>进入用户和角色。

您的类(class)必须遵循以下内容:

用户类:

public class User
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }

    public User()
    {
        this.UserRoles = new Collection<UserRole>();
    }
}

角色类:

public class Role
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }

    public Role()
    {
        this.UserRoles = new Collection<UserRole>();
    }
}

UserRole 类:

public class UserRole
{
    public int Id { get; set; }

    public int UserId { get; set; }

    public User User { get; set; }

    public int RoleId { get; set; }

    public Role Role { get; set; }
}

无需配置,EF 将使用默认约定并为您创建所需的所有表。

当你加入实体时很常见UserRole没有数据属性,我的意思是只有外键,然后你可以删除它并让 UserRole如下:

用户类:

public class User
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Role> Roles { get; set; }

    public User()
    {
        this.Roles = new Collection<Role>();
    }
}

角色类:

public class Role
{
    public int Id { get; set; }

    public string Name { get; set; }

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

    public Role()
    {
        this.Users = new Collection<User>();
    }
}

同样不需要配置,EF 将使用默认约定为您创建表和连接表。

要了解很多关于 EF 的知识,我推荐这个网站 Entity Framework Tutorials如果您可以阅读以下两本书:

  • 编程 Entity Framework :DbContext

  • 编程 Entity Framework :代码优先

关于c# - Entity Framework 中的多对多关系有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35322739/

相关文章:

Asp.Net Identity 查找不在角色中的用户

entity-framework - 根据另一个字段的值增加 Entity Framework 中的字段

c# - 如何将整数转换为无符号 64 位整数

c# - .Net Core 1.1 在记录时不序列化对象

c# - C# 中的解析器。如何从字符串填充类

asp.net-mvc - 在 MVC 创建 View 上保存多对多关系数据

c# - 通过查询结果阻止访问

c# - 无法确定保存订单时关系的主体端 - EF6

c# - 填充数组时出现 StackoverflowException

c# - 使用 Entity Framework Fluent 语法或内联语法编写递归 CTE