【问题标题】:Insert constraint failed nFOREIGN KEY constraint failed While Seeding Data插入约束失败 nFOREIGN KEY 约束在播种数据时失败
【发布时间】:2016-11-28 15:49:39
【问题描述】:

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

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() 之后才出现。

【问题讨论】:

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


    【解决方案1】:
    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();
     }
    

    希望这行得通..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2018-11-06
      相关资源
      最近更新 更多