简体   繁体   English

实体框架 - 多对多?

[英]Entity Framework - Many to many?

I'm defining a many-to-many relationship as follows: 我正在定义如下的多对多关系:

    modelBuilder.Entity<GameSessionEntry>().
         HasMany(c => c.Users).
         WithMany(p => p.GameSessionEntries).
         Map(
          m =>
          {
              m.MapLeftKey("SessionId");
              m.MapRightKey("UserId");
              m.ToTable("UserSessions");
          });

However, I keep getting: 但是,我一直在:

The Foreign Key on table 'UserSessions' with columns 'UserId' could not be created because the principal key columns could not be determined. 无法创建具有列'UserId'的表'UserSessions'上的外键,因为无法确定主键列。 Use the AddForeignKey fluent API to fully specify the Foreign Key. 使用AddForeignKey fluent API完全指定外键。

I'm new to database work and the EntityFramework in general - what is it asking me to do? 我是数据库工作和EntityFramework的新手 - 它要求我做什么?

It's the recurring confusion with left and right, see this explanation by Slauma. 这是左右反复出现的混乱,请参阅Slauma的这个解释。 So you just have to turn around the key names: 所以你只需要转动关键名称:

  m.MapLeftKey("UserId");      // Property in the HasMany call
  m.MapRightKey("SessionId");  // Property in the WithMany call

This is how I usually go about creating a many to many table (note this requires no fluent api configuration) 这就是我通常创建多对多表的方法(注意这不需要流畅的api配置)

public class User
{
    public int Id { get; set; }
    public virtual ICollection<UserSession> UserSessions { get; set; }
}

public class Session
{
    public int Id { get; set; }
    public virtual ICollection<UserSession> UserSessions { get; set; }
}

public class UserSession
{
    [Key]
    [Column(Order = 1)]
    public int UserId { get; set; }

    [Key]
    [Column(Order = 2)]
    public int SessionId{ get; set; }

    public virtual User User { get; set; }
    public virtual Session Session { get; set; }
}

Instead of fiddling around with a many-many relationship you should rewrite it to a weak entity set. 您应该将其重写为弱实体集,而不是摆弄多对多关系。

If you have for instance this relationship: 如果你有这种关系:

在此输入图像描述

You can redesign it to a weak entity set: 您可以将其重新设计为弱实体集:

在此输入图像描述

By doing this you get rid of the many-many relationship and don't have to store the same data in multiple tables. 通过这样做,您可以摆脱多对多的关系,而不必将相同的数据存储在多个表中。

For more information: http://fileadmin.cs.lth.se/cs/Education/EDA216/lectures/dbtoh4.pdf Read the lecture slides about "The Relational Data Model" starting on slide 87/360. 有关更多信息,请访问: http ://fileadmin.cs.lth.se/cs/Education/EDA216/lectures/dbtoh4.pdf从幻灯片87/360开始阅读关于“关系数据模型”的演讲幻灯片。

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

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