Home > Enterprise >  How to create a connection between two objects, reference to one and to many in EF Core
How to create a connection between two objects, reference to one and to many in EF Core

Time:06-22

I have two classes

class Role
{ 
    string Id { get; set; }
    string Name { get; set; }
}

class Permission
{ 
    string Id { get; set; }
    string Name { get; set; }
}

I want to create a table for assign multiple permission to a role

class RoleAssignedPermissions
{ 
    string Id { get; set; }
    Role Role { get; set; }
    ICollection<Permission> Permissions { get; set; }
}

In OnModelCreating I have:

modelBuilder.Entity<Role>(entity =>
            {
                entity.HasKey(x => x.Id);
            });
modelBuilder.Entity<Permission>(entity =>
            {
                entity.HasKey(x => x.Id);
            });
modelBuilder.Entity<RoleAssignedPermissions>(entity =>
            {
                entity.HasKey(x => x.Id);
                entity.HasOne(x => x.Role);                    
                entity.HasMany(x => x.Permissions);
            });

In this case is by adding a migration are generated three tables, roles table is ok with id and name

But Permissions instead of id and name, appear new column RoleAssignedPermissionsId, and in table RoleAssignedPermissions id and roleId

But should be in RoleAssignedPermissions a column for collection of Permissions

CodePudding user response:

Here are the entities. You can do like this

class Role
{ 
    string Id { get; set; }
    string Name { get; set; }
    public virtual ICollection<Permission> Permissions {get; set;}
}

class Permission
{ 
    string Id { get; set; }
    string Name { get; set; }
    [ForeignKey("Role")]
    public string RoleId {get; set;}
    public virtual Role Role {get; set;}
}

CodePudding user response:

public class Role
{ 
    string Id { get; set; }
    string Name { get; set; }
    public virtual ICollection<Permission> Permissions {get; set;}
}

 public class Permission
 { 
   string Id { get; set; }
   string Name { get; set; }
   public string RoleId {get; set;}
   public virtual Role Role {get; set;}
 }

  public class RoleConfiguration : IEntityTypeConfiguration<Role>{
      public void Configure(EntityTypeBuilder<Role> builder)
      {
          builder.HasMany(p => p.Permissions).WithOne(p => .Role).HasForeignKey(p => p.RoleId );
      }
    }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.ApplyConfiguration(new RoleConfiguration ());
    
}
  • Related