繁体   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?

我需要在Entity Framework Code First中实现多对多关系,并将该关系映射到第三个表。 我想在此表中添加其他一些字段,例如自动递增的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"));
    }
}

但是,Entity Framework会生成一个表,该表使用了我传递的错误名称,以及我传递给映射的错误名称导航属性。

表“ RoleUsers”的名称和导航属性的名称为“ User_Id”和“ Role_Id”。

如何实现正确的映射名称以及如何向UserRoles表添加其他一些属性?

由于需要添加其他属性来描述关系,因此必须将多对多关联视为两个一对多关联:

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

组态:

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