【发布时间】:2015-12-21 20:57:52
【问题描述】:
第一次创建数据库并运行Seed 方法工作正常。当数据已经在数据库中时,它会在第二次运行时引发错误。
我还注意到,当我将属性分配给实体时,它的PropertyId 没有更新并保持为空。
这是我的代码。
protected override void Seed(StreetStats.Data.StreetStatsDbContext context)
{
if (System.Diagnostics.Debugger.IsAttached == false)
System.Diagnostics.Debugger.Launch();
using (context.Database.BeginTransaction())
{
try
{
Worker worker = new Worker()
{
Name = "Worker 1",
};
context.Workers.AddOrUpdate(w => w.Name, worker);
context.SaveChanges(); //Worker gets Id assigned to the existing worker with the same name in DB
Job job = new Job()
{
Name = "Job 1",
Worker = worker
};
context.Jobs.AddOrUpdate(j => j.Name, job);
context.SaveChanges(); //WorkerId is null for some reason
MonitoringTask monitoringTask = new MonitoringTask
{
Job = job,
Name = "Task 1"
};
context.MonitoringTasks.AddOrUpdate(mt => mt.Name, monitoringTask);
context.SaveChanges(); //Throws exception
Area area = new Area
{
MonitoringTask = monitoringTask,
Name = "Area 1"
};
context.Areas.AddOrUpdate(a => a.Name, area);
context.SaveChanges();
context.Database.CurrentTransaction.Commit();
}
catch (Exception)
{
context.Database.CurrentTransaction.Rollback();
throw;
}
}
}
这是第三次 SaveChanges 上的异常消息:
UPDATE 语句与 FOREIGN KEY 约束“FK_dbo.MonitoringTasks_dbo.Jobs_JobId”冲突。冲突发生在数据库“StreetStats”、表“dbo.Jobs”、列“Id”中。
每个 FK 关系看起来都像
Worker Worker { get; set; }
Int64 WorkerId { get; set; }
【问题讨论】:
标签: c# .net sql-server entity-framework orm