当我尝试添加迁移时,出现以下异常:
无法添加实体类型“流派”的种子实体,因为它设置了导航“子流派”。要种子关系,您需要将相关实体种子添加到“流派”并指定外键值 {'ParentId'}
我如何正确设置种子EntityFrameworkCore 2.2
我有下一个实体
public class Genre
{
[Key] public int Id { get; set; }
[Required] [MaxLength(50)] public string Name { get; set; }
public virtual ICollection<GameGenre> GameGenre { get; set; } = new List<GameGenre>();
public int? ParentId { get; set; }
public virtual Genre ParentGenre { get; set; }
public virtual ICollection<Genre> SubGenres { get; set; } = new List<Genre>();
}
数据库上下文
public class OnlineGameContext : DbContext
{
public OnlineGameContext(DbContextOptions<OnlineGameContext> options)
: base(options)
{
}
public DbSet<Genre> Genres { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Genre>()
.HasMany(u => u.SubGenres)
.WithOne(p => p.ParentGenre)
.HasForeignKey(p => p.ParentId);
modelBuilder.Entity<Genre>().HasData(DefaultGenresFactories.Action);
base.OnModelCreating(modelBuilder);
}
}
工厂
public static class DefaultGenresFactories
{
public static Genre Action =>
new Genre
{
Id = 5,
Name = "Action",
SubGenres = DefaultSubGenresFactories.Action
};
}
public static class DefaultSubGenresFactories
{
public static ICollection<Genre> Action => new List<Genre>
{
new Genre
{
Id = 15,
Name = "FPS",
ParentId = 5
},
new Genre
{
Id = 16,
Name = "TPS",
ParentId = 5
},
new Genre
{
Id = 17,
Name = "Misc",
ParentId = 5
}
};
}