[英]How do I seed a foreign key one-to-many list relation?
I have class/table:我有课/表:
public class Song
{
[Key]
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
[ForeignKey("FK_SongTags")]
public List<Tag> Tags { get; set; }
}
Where class/table Tag is:类/表标签在哪里:
[Table("Tags")]
public class Tag
{
[Key]
public string Name { get; set; }
}
In my Context I call this seed:在我的上下文中,我称这个种子为:
modelBuilder.Entity<Song>().HasData(new List<Song>
{
new Song { Id = Guid.NewGuid(), Name = "Some random song", Tags = new List<Tag> { "pop", "rock" } }
});
When I do do.net ef database update , I get:当我执行do.net ef database update时,我得到:
The seed entity for entity type 'Song' cannot be added because it has the navigation 'Tags' set.
无法添加实体类型“歌曲”的种子实体,因为它设置了导航“标签”。 To seed relationships, add the entity seed to 'Tag' and specify the foreign key values {'FK_SongTags'}.
要播种关系,请将实体种子添加到“标签”并指定外键值 {'FK_SongTags'}。 Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values.
考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看涉及的属性值。
How do I solve this error?我该如何解决这个错误?
You need many-to-many relations since one song can have several tags, and each tag can be used for another songs too.您需要多对多关系,因为一首歌曲可以有多个标签,每个标签也可以用于另一首歌曲。 Try this:
尝试这个:
public class Song
{
[Key]
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public virtual List<Tag> Tags { get; set; }
}
[Table("Tags")]
public class Tag
{
[Key]
public string Name { get; set; }
public virtual List<Song> Songs{ get; set; }
}
you will have to make an initial migration to db after making changes.进行更改后,您将必须初始迁移到数据库。
but if you still think that you need one to many try this但如果你仍然认为你需要一对多试试这个
[Table("Tags")]
public class Tag
{
[Key]
public string Name { get; set; }
public Guid SongId {get; set;}
public virtual Song Song {get; set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.