Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 具有多个一对多关系的表_Entity Framework_Ef Code First_Entity Framework Migrations - Fatal编程技术网

Entity framework 具有多个一对多关系的表

Entity framework 具有多个一对多关系的表,entity-framework,ef-code-first,entity-framework-migrations,Entity Framework,Ef Code First,Entity Framework Migrations,我有一个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()

我有一个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...
}
公共课堂笔记
{
[关键]
公共Guid Id{get;set;}
公共字符串NoteText{get;set;}
公共字符串作者{get;set;}
公共日期时间?CreationDate{get;set;}
}
公开课Foo
{
公共食物(
{
Notes=新的HashSet();
}
[关键]
公共Guid Id{get;set;}
公共虚拟ICollection注释{get;set;}
//其他属性已删除。。。
}
公共类酒吧
{
公共酒吧()
{
Notes=新的HashSet();
}
[关键]
公共Guid Id{get;set;}
公共虚拟ICollection注释{get;set;}
//其他属性已删除。。。
}
如您所见,
Foo
Bar
都有自己的
注释列表
,但是
注释
属于
Foo
Bar

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


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

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

在笔记课上:

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; }
}
公共课堂笔记
{
[关键]
公共Guid Id{get;set;}
公共字符串NoteText{get;set;}
公共字符串作者{get;set;}
公共日期时间?CreationDate{get;set;}
公共日期时间?CreationDate{get;set;}
公共虚拟ICollection Foos{get;set;}
公共虚拟ICollection条{get;set;}
}

希望这有帮助

我真的想要一对多的关系,因为一个音符只属于一个Foo(或Bar),而一个Foo(或Bar)可以有很多音符。另外,我不需要Notes中的导航属性。您还有其他建议吗?您可以尝试[此链接](),您需要使用
.WithMany
功能或
.Map
EntityTypeConfiguration
一起使用。该链接提供了有用的信息。我还没有看到任何使用注释的方法。