【问题标题】:One-to-one plus many-to-many relationships with the same object not building correctly与同一对象的一对一加多对多关系未正确构建
【发布时间】:2011-07-25 22:52:55
【问题描述】:

我正在使用 Entity Framework 4 代码优先方法在 ASP MVC 3 中设计我的数据库,但遇到了一些麻烦。我有一个 POCO 类如下:

public class User
{
    [Key]
    public Guid UserID { get; set; }
    public string UserName { get; set; }
    public DateTime CreationDate { get; set; }
    public string Email { get; set; }
    public int Points { get; set; }
    public Session ActiveSession { get; set; }
    public ICollection<Session> InSessions { get; set; }
}

Session 作为我在别处定义的另一个模型类,ICollection&lt;User&gt; 作为其属性之一。如果我从User 类中删除public Session ActiveSession { get; set; } 属性,则多对多映射和UserSessions 中间表构造正确,但是当我重新添加ActiveSession 一对一映射时,它打破了多对多映射,并且没有构造中间表。相反,Users 表对于ActiveSessionInSessions 属性都有一个指向Sessions 表的外键。任何想法为什么会发生这种情况?

【问题讨论】:

  • 你能显示你的映射代码吗?
  • @Eranga 以上内容差不多。我使用的是代码优先方法,所以我没有 edmx 模型,到目前为止,我不需要使用任何映射流式 API 或属性。 EF 正在为我构建数据库,因此我不必映射到任何现有表。

标签: asp.net-mvc-3 entity-framework ef-code-first many-to-many


【解决方案1】:

在您的情况下,EF 认为 Session 类中的 ICollection&lt;User&gt; 是由 ActiveSession 创建的一对多关系的 Many 结尾。

所以你需要手动配置

modelBuilder.Entity<User>().HasOptional(u => u.ActiveSession)
   .WithMany()
   .Map(u => u.MapKey("ForeignKeyColumn"));

modelBuilder.Entity<User>()
   .HasMany(u => u.InSessions)
   .WithMany(s => s.Users)
   .Map(m =>
       {
           m.ToTable("UserSessions");
           m.MapLeftKey("UserID");
           m.MapRightKey("SessionID");
       });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-13
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2016-07-23
    • 2014-07-02
    相关资源
    最近更新 更多