【发布时间】:2013-12-04 21:41:13
【问题描述】:
所以我尝试在 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
}
);
}
}
我的问题是,种子方法不是更新/对未更改的记录执行任何操作,而是复制每一行。我尝试手动设置 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++;
}
}
【问题讨论】:
-
什么是
AddOrUpdate? -
@lazyberezovsky msdn.microsoft.com/en-us/library/hh846520(v=vs.103).aspx
-
有趣.. 不知道,谢谢
-
你能展示一下你的实际结果吗?是
6密苏里州记录与RequestType相同等于1吗? -
@lazyberezovsky 不完全是。这是另一组状态 1-6,但我已经用更好的解释更新了这个问题。
标签: c# ef-code-first entity-framework-5