0

我有一个 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,但 aNote属于 aFoo a Bar

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

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

4

1 回答 1

0

这已经在另一个帖子中得到了回答!但是为了节省您在谷歌上搜索的时间,您将获得一个一对多的关联,这是正确的。您希望代码中存在多对多关系,因此您需要做的是:

在你的笔记课上:

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; }
}

希望这可以帮助

于 2012-12-20T13:19:17.973 回答