Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 实体框架-如何配置用户角色多对多关系_Entity Framework_Ef Code First_Ef Code First Mapping - Fatal编程技术网

Entity framework 实体框架-如何配置用户角色多对多关系

Entity framework 实体框架-如何配置用户角色多对多关系,entity-framework,ef-code-first,ef-code-first-mapping,Entity Framework,Ef Code First,Ef Code First Mapping,下面是用户实体的定义,有一个导航属性角色 public class User { public User() { Roles = new List<Role>(); } public string Id { get; set; } public string Username { get; set; } public virtual IColl

下面是用户实体的定义,有一个导航属性角色

    public class User
    {
        public User()
        {
            Roles = new List<Role>();
        }

        public string Id { get; set; }

        public string Username { get; set; }

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

我想定义多对多关系并生成一个关系表UserRole,它使用UserId作为左键,使用RoleId作为右键,那么如何编写配置代码呢?

用户:

public class User
{
    public User()
    {
        Roles = new List<Role>();
    }

    public string Id { get; set; }
    public string Username { get; set; }
    public virtual ICollection<UserRole> Roles { get; set; }
}
用户角色:

public class Role
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}
public class UserRole
{
    public string Id { get; set; }
    public string UserId { get; set; }
    public string RoleId{ get; set; }

    public virtual User User { get; set; }
    public virtual Role Role { get; set; }
}
在dbcontext中重写OnModelCreating的
方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<User>()
        .HasMany(c => c.Roles )
        .WithMany()                 
        .Map(x =>
        {
            x.MapLeftKey("UserId");
            x.MapRightKey("RoleId");
            x.ToTable("UserRoles");
        });
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
基于模型创建(modelBuilder);
modelBuilder.Entity()
.HasMany(c=>c.角色)
.有很多
.Map(x=>
{
x、 MapLeftKey(“用户ID”);
x、 MapRightKey(“RoleId”);
x、 ToTable(“用户角色”);
});
}

是否需要UserRole类?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<User>()
        .HasMany(c => c.Roles )
        .WithMany()                 
        .Map(x =>
        {
            x.MapLeftKey("UserId");
            x.MapRightKey("RoleId");
            x.ToTable("UserRoles");
        });
}