簡體   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