插入约束失败nFOREIGN KEY约束失败播种数据时

时间:2016-11-28 15:49:40

标签: entity-framework sqlite ef-code-first

我正在尝试播种一些示例数据

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();
 }

我得到这个异常约束失败FOREIGN KEY约束失败,我无法弄清楚我在这里做错了什么。

我在第一次插入后尝试调用了context.SaveChanges()并且它很好。但错误仅在第二个context.SaveChanges()之后才会出现。

1 个答案:

答案 0 :(得分:0)

protected override void Seed(AppContext context)
 {
      Condition condition1 = new Condition();
      condition1.Id=1; 
      condition1.Name = "Cond1";
      Entity.Entity newEntity1 = new Entity.Entity();
      newEntity1.Name = "Test1";
      newEntity1.ConditionId=1
      newEntity1.Condition = condition1;
      context.Entities.Add(newEntity1);

      Condition condition2 = new Condition();
      condition2.Id=2
      condition2.Name = "Cond2";
      Entity.Entity newEntity2 = new Entity.Entity();
      newEntity2.Name = "Test Entity 2";
      newEntity2.ConditionId=2; 
      newEntity2.Condition = condition2;
      context.Entities.Add(newEntity2);
      context.SaveChanges();
 }

希望这有效..