1
我試圖種子一些示例數據插入約束失敗nFOREIGN KEY約束失敗儘管播種數據
public class Condition
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
public int ConditionId { get; set; }
public virtual Condition Condition { get; set; }
}
,並在我的種子的方法..
protected override void Seed(AppContext context)
{
Condition condition1 = new Condition();
condition1.Name = "Cond1";
Entity.Entity newEntity1 = new Entity.Entity();
newEntity1.Name = "Test1";
newEntity1.Condition = condition1;
context.Entities.Add(newEntity1);
Condition condition2 = new Condition();
condition2.Name = "Cond2";
Entity.Entity newEntity2 = new Entity.Entity();
newEntity2.Name = "Test Entity 2";
newEntity2.Condition = condition2;
context.Entities.Add(newEntity2);
context.SaveChanges();
}
我得到這個異常限制外國失敗KEY約束失敗,我無法弄清楚我在這裏做了什麼錯誤。
我試着在第一次插入之後調用context.SaveChanges(),它很好。但僅在第二個context.aveChanges()後纔會出現錯誤。