Entity framework 具有多个一对多关系的表
我有一个EF代码优先模型,其中一个表与其他表具有多个一对多关系: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()
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
一起使用。该链接提供了有用的信息。我还没有看到任何使用注释的方法。