因此,我正在尝试使用 EF5 中的种子数据填充表。我有所有 50 个州和 DC 的枚举。我还有一个 ID 为 1-6 的 RequestTypes 查找表。它会是这样的:
+----+----------+-------------+------------+
| Id | State | SurveyId | RequestType|
+----+----------+-------------+------------+
| 1 | Alabama | 0 | 1 |
| 2 | Alabama | 0 | 2 |
| 3 | Alabama | 0 | 3 |
| 4 | Alabama | 0 | 4 |
| 5 | Alabama | 0 | 5 |
| 6 | Alabama | 0 | 6 |
+----+----------+-------------+------------+
表示这个表的模型:
public class StateSurveyAssignment{
public long Id { get; set; }
public string State { get; set; }
public long RequestTypeId { get; set; }
public long SurveyId { get; set; }
}
以及在 Configuration.cs 中为数据库播种的代码:
foreach (var state in Enum.GetValues(typeof(State))) {
foreach (var type in context.RequestTypes){
context.StateSurveyAssignments.AddOrUpdate(
ssa => ssa.Id,
new StateSurveyAssignment{
State = state.ToString(),
RequestTypeId = type.Id
}
);
}
}
我的问题是,seed 方法不是更新/不对未更改的记录做任何事情,而是复制每一行。我曾尝试手动设置 Id,但没有成功。
编辑:
这是数据库复制的样子:
+----+----------+-------------+------------+
| Id | State | SurveyId | RequestType|
+----+----------+-------------+------------+
| 1 | Alabama | 0 | 1 |
| 2 | Alabama | 0 | 2 |
| 3 | Alabama | 0 | 3 |
| 4 | Alabama | 0 | 4 |
| 5 | Alabama | 0 | 5 |
| 6 | Alabama | 0 | 6 |
| ...| ... | ... | ... |
|307 | Alabama | 0 | 1 |
|308 | Alabama | 0 | 2 |
|309 | Alabama | 0 | 3 |
|310 | Alabama | 0 | 4 |
|311 | Alabama | 0 | 5 |
|312 | Alabama | 0 | 6 |
+----+----------+-------------+------------+
我的解决方案
我发誓我曾经尝试过设置自己的 Id,但根据答案再次尝试,它似乎奏效了。我的最终解决方案:
int counter = 1;
foreach (var state in Enum.GetValues(typeof(State))) {
foreach (var type in context.RequestTypes){
context.StateSurveyAssignments.AddOrUpdate(
ssa => ssa.Id,
new StateSurveyAssignment{
Id = counter,
State = state.ToString(),
RequestTypeId = type.Id
}
);
counter++;
}
}
最佳答案
问题可能是 StateSurveyAssignment
类中的 Id
属性是数据库中的标识列。
这意味着每一行都不是唯一的。
例如,您尝试使用 AddOrUpdate()
var model = new StateSurveyAssignment
{
State = "Alabama",
RequestTypeId = 1L,
SurveyId = 0L
};
那么每个条目都会有一个不同的 Id
,因此您会有重复项。
关于c# - EF Code First 配置复制记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20386616/