简体   繁体   中英

EF Code First many-to-many: how to specify name of th third table and add some other properties to it?

I need to implement the many-to-many relationship in the Entity Framework Code First, and map this relationship to the third table. And I want to add to this table some other fields such as autoincremented Id and the AppointmentDateTime for exaple:

public class User {
    public int Id { get; set; }
    // some other properties ......
    public virtual List<Role> Roles { get; set; }
}

public class UserTypeConfiguration : EntityTypeConfiguration<User> {
    public UserTypeConfiguration() {
        HasKey(k => k.Id);
        Property(p => p.Email).IsRequired();
        //[∞ — ∞]
        HasMany<Role>(u => u.Roles).WithMany(r => r.Users).Map(m => m.MapLeftKey("UserId").MapRightKey("RoleId").ToTable("UserRoles"));
    }
}

But Entity Framework generates a table with the wrong name that which I have passed, and wrong names navigation proiperties I have passed to the mapping.

The name of table "RoleUsers" and the names of navigation proiperties are "User_Id" and "Role_Id".

How to implement correct names of mapping and how to add some other properties to the UserRoles table?

Since you need to add additional properties to describe the relationship, you have to consider many-to-many association as two one-to many ones:

public class User
{
    // other properties omitted
    public virtual List<UserRole> UserRoles { get; set; }
}

public class Roles
{
    // other properties omitted
    public virtual List<UserRole> UserRoles { get; set; }
}

public class UserRole
{
    public int Id { get; set; }
    public DateTime AppointmentDateTime { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
    public int RoleId { get; set; }
    public Role Role { get; set; }
}

Configuration:

public class UserRoleConfiguration : EntityTypeConfiguration<UserRole> 
{
    public UserRoleConfiguration()
    {
        // scalar properties config omitted
        HasRequired(_ => _.User)
            .WithMany(_ => _.UserRoles)
            .HasForeignKey(_ => _.UserId);

        HasRequired(_ => _.Role)
            .WithMany(_ => _.UserRoles)
            .HasForeignKey(_ => _.RoleId);

        ToTable("UserRoles");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM