简体   繁体   English

EF Code First多对多:如何指定第三个表的名称并为其添加其他属性?

[英]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. 我需要在Entity Framework Code First中实现多对多关系,并将该关系映射到第三个表。 And I want to add to this table some other fields such as autoincremented Id and the AppointmentDateTime for exaple: 我想在此表中添加其他一些字段,例如自动递增的Id和AppointmentDateTime例如:

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. 但是,Entity Framework会生成一个表,该表使用了我传递的错误名称,以及我传递给映射的错误名称导航属性。

The name of table "RoleUsers" and the names of navigation proiperties are "User_Id" and "Role_Id". 表“ RoleUsers”的名称和导航属性的名称为“ User_Id”和“ Role_Id”。

How to implement correct names of mapping and how to add some other properties to the UserRoles table? 如何实现正确的映射名称以及如何向UserRoles表添加其他一些属性?

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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