【问题标题】:Table with several one-to-many relationships具有多个一对多关系的表
【发布时间】:2012-12-20 11:56:28
【问题描述】:

我有一个 EF 代码优先模型,其中一个表与其他表具有多个一对多关系:

public class Note
{
  [Key]
  public Guid Id { get; set; }
  public string NoteText { get; set; }
  public string Author { get; set; }
  public DateTime? CreationDate { get; set; }
}

public class Foo
{
  public Foo()
  {
    Notes = new HashSet<Note>();
  }

  [Key]
  public Guid Id { get; set; }
  public virtual ICollection<Note> Notes { get; set; }
  // other properties ommited...
}

public class Bar
{
  public Bar()
  {
    Notes = new HashSet<Note>();
  }

  [Key]
  public Guid Id { get; set; }
  public virtual ICollection<Note> Notes { get; set; }
  // other properties ommited...
}

如您所见,Foo 和Bar 都有自己的Notes 列表,但Note 属于Foo 或 Bar。

在为迁移搭建脚手架时,EF 在Notes 表中为Foo 和Bar 创建了一个外键,我认为这是不正确的。相反,我希望在Foo 和Notes 之间创建一个链接表,并在Bar 和Notes 之间创建另一个链接表。

有没有办法自动做到这一点?还是我必须在我的代码优先实现中手动创建这些类?

【问题讨论】:

    标签: entity-framework ef-code-first entity-framework-migrations


    【解决方案1】:

    这个other post已经回答了! 但是为了省去你在谷歌上搜索的时间,你得到了一个一对多的关联,这是正确的。你想在你的代码中建立多对多的关系,所以你需要做的是:

    在你的笔记课上:

    public class Note
    {
      [Key]
      public Guid Id { get; set; }
      public string NoteText { get; set; }
      public string Author { get; set; }
      public DateTime? CreationDate { get; set; }
      public DateTime? CreationDate { get; set; }
      public virtual ICollection<Foo> Foos { get; set; }
      public virtual ICollection<Bar> Bars { get; set; }
    }
    

    希望对你有帮助

    【讨论】:

    • 我真的想要一个一对多的关系,因为一个音符只属于一个 Foo(或 Bar),而一个 Foo(或 Bar)可以有多个 Notes。另外,我不需要 Notes 中的导航属性。您还有其他建议吗?
    • 您可以尝试[此链接] (weblogs.asp.net/manavi/archive/2011/05/17/…),您需要使用.WithMany 函数或.Map 与EntityTypeConfiguration 一起使用。该链接包含有用的信息。我还没有看到任何使用注释的方法。
    猜你喜欢
    • 1970-01-01
    • 2012-06-15
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2016-11-10
    • 1970-01-01
    相关资源
    最近更新 更多