简体   繁体   English

ForeignKey-多对多(EntityFramework)中的定义?

[英]ForeignKey - Definition in Many-to-Many (EntityFramework)?

Because I don't like the naming convention the entityFramework (Code first) uses I usually use a foreignKey property to assign my own property: 因为我不喜欢实体命名约定,所以EntityFramework(首先使用代码)使用的是我通常使用的foreignKey属性来分配自己的属性:

public class User {
   public virtual Customer Customer { get; set; }
   [ForeignKey("Customer")]
   public Guid CustomerId { get; set; }
}

Works just fine, a column "CustomerId" is created inside the "User"-Table. 工作正常,在“用户”-表内创建了“ CustomerId”列。

But how do I achieve the same when I need a many-to-many relationship? 但是,当我需要多对多关系时,如何实现相同目标?

public class User {
       public virtual ICollection<Role> Roles { get; set; }
    }

public class Role {
   public virtual ICollection<User> Users { get;set; }
}

This results in a Table "UserRole" which contains "User_id" and "Role_Id". 这将导致包含“ User_id”和“ Role_Id”的表“ UserRole”。

Still, I prefer "UserId" and "RoleId". 不过,我还是更喜欢“ UserId”和“ RoleId”。 I could just create a UserRole-Class myself containing the references to User and Role but there should be a more elegant way. 我可以自己创建一个UserRole-Class,其中包含对User和Role的引用,但是应该有一种更优雅的方法。 Is there any? 有没有?

You could configure that many-to-many relationship on your context using Fluent Api as I show below: 您可以使用Fluent Api在您的上下文中配置多对多关系,如下所示:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

   modelBuilder.Entity<User>()
               .HasMany<Role>(u => u.Roles)
               .WithMany(c => c.Users)
               .Map(cs =>
                        {
                            cs.MapLeftKey("UserId");
                            cs.MapRightKey("RoleId");
                            cs.ToTable("UserRoles");
                        });

}

This way you could name the junction table and the FK columns with the names that you want. 这样,您可以使用所需的名称来命名联结表和FK列。

Another way is create an entity that represent the junction table and stablish two one-to-many relationships with User and Role , but if you don't need to add extra columns to the junction table, It's recommended use the first variant, but you can find some advantages in map this table explicitly. 另一种方法是创建一个表示联结表的实体,并使用UserRole建立两个一对多的关系,但是如果不需要在联结表中添加额外的列,建议使用第一个变体,但是可以在显式映射此表中找到一些优势

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

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