我正在使用 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只做你想做的事。
无论如何,一些澄清:
-
UserRole
是User
之间的关联实体和Role
-
UserRole
需要Role
-
UserRole
需要User
UserRole
表示一个 User
之间的组合和一个Role
.您可以有很多这样的实例,就像 User
一样。有很多Role
.这就是为什么在用 Fluent API 翻译它之前你必须删除 Roles
和 Users
您放入 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
没有数据属性,我的意思是只有外键,然后你可以删除它并让 User
和 Role
如下:
用户类:
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/