【问题标题】:ForeignKey - Definition in Many-to-Many (EntityFramework)?ForeignKey - 多对多(EntityFramework)中的定义?
【发布时间】:2015-04-09 22:40:10
【问题描述】:

因为我不喜欢 entityFramework(代码优先)使用的命名约定,所以我通常使用 foreignKey 属性来分配我自己的属性:

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

工作得很好,在“用户”表中创建了一个“客户 ID”列。

但是,当我需要多对多关系时,我该如何实现呢?

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

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

这会产生一个表“UserRole”,其中包含“User_id”和“Role_Id”。

不过,我更喜欢“UserId”和“RoleId”。我可以自己创建一个 UserRole-Class,其中包含对 User 和 Role 的引用,但应该有一种更优雅的方式。有吗?

【问题讨论】:

  • 由于该链接表未显示在您的代码中,因此您将无法使用属性。你看过流畅的配置吗?

标签: c# entity-framework


【解决方案1】:

您可以使用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");
                        });

}

这样,您可以使用您想要的名称命名联结表和 FK 列。

另一种方法是创建一个表示联结表的实体,并与UserRole建立两个一对多关系,但如果不需要在联结表中添加额外的列,建议使用第一个变体,但您可以在映射此表中明确找到一些 advantages

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 2012-08-27
    相关资源
    最近更新 更多