我正在定义如下的多对多关系:
modelBuilder.Entity<GameSessionEntry>().
HasMany(c => c.Users).
WithMany(p => p.GameSessionEntries).
Map(
m =>
{
m.MapLeftKey("SessionId");
m.MapRightKey("UserId");
m.ToTable("UserSessions");
});
然而,我一直在:
表'UserSessions'上的外键,列'UserId'可以 不能创建,因为主键列不能 决心。使用AddForeignKey fluent API完全指定 外键。
我是数据库工作和EntityFramework的新手 - 它要求我做什么?
答案 0 :(得分:1)
这是左右反复出现的混乱,请参阅Slauma的this解释。所以你只需要转动关键名称:
m.MapLeftKey("UserId"); // Property in the HasMany call
m.MapRightKey("SessionId"); // Property in the WithMany call
答案 1 :(得分:1)
这就是我通常创建多对多表的方法(注意这不需要流畅的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; }
}
答案 2 :(得分:0)
您应该将其重写为弱实体集,而不是摆弄多对多的关系。
如果您有这种关系:
您可以将其重新设计为弱实体集:
通过这样做,您可以摆脱多对多的关系,而不必将相同的数据存储在多个表中。
有关详细信息:http://fileadmin.cs.lth.se/cs/Education/EDA216/lectures/dbtoh4.pdf 从幻灯片87/360开始阅读关于“关系数据模型”的演讲幻灯片。