【发布时间】:2019-02-17 17:20:49
【问题描述】:
我刚刚遇到了一个问题,让人想起先有鸡还是先有蛋的情况。
我正在尝试在 EF 2.1.3 中播种数据。我有一个名为“示例”的课程。
public class Sample
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsActive { get; set; }
public bool IsVisible { get; set; }
}
我有以下种子方法:
builder.HasData(
new Sample {Id=1, IsActive = true, IsVisible = true, Name = "Test 1" },
new Sample { Id = 2, IsActive = true, IsVisible = true, Name = "Test 2" },
new Sample { Id = 3, IsActive = true, IsVisible = true, Name = "Test 3" }
);
现在,这似乎在我第一次生成迁移时工作正常
但是,现在每次我运行 Add-Migration 命令时都会收到此错误:
The seed entity for entity type 'Sample' cannot be added because another seed entity with the same key value for {'Id'} has already been added. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
从种子数据中删除 Id 值 - 导致此错误:
The seed entity for entity type 'Sample' cannot be added because there was no value provided for the required property 'Id'.
【问题讨论】:
-
没关系 - 只是想通了。我发布了一个相当简单的例子。在我的情况下,我的实体实际上是从基类继承的。我已经为基本抽象类添加了一个映射 - 并且 EF 从每个具体类型的表切换到每个层次结构的表。错误消息只是我们的副产品。我已经注释掉了所有的种子数据语句——生成的映射讲述了一个故事,因此重复的主键错误(如果所有的记录都存储在一个表中——你不能有重复的 ID 是有道理的......)
-
未来的自我提醒 - 总是发布完整的故事。
标签: entity-framework-core entity-framework-migrations ef-core-2.1