首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Insert constraint failed nFOREIGN KEY constraint在设定数据种子时失败

Insert constraint failed nFOREIGN KEY constraint在设定数据种子时失败
EN

Stack Overflow用户
提问于 2016-11-28 23:49:40
回答 1查看 107关注 0票数 2

我正在尝试播种一些样本数据。

代码语言:javascript
复制
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; }
}

在我的种子方法中..

代码语言:javascript
复制
 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();
 }

我得到了这个异常约束失败的外键约束失败,我不知道我在这里做错了什么。

我也试着在第一次插入之后调用context.SaveChanges(),它运行得很好。但该错误仅在第二个context.SaveChanges()之后出现。

EN

回答 1

Stack Overflow用户

发布于 2016-11-29 17:52:21

代码语言:javascript
复制
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();
 }

希望这能行得通。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40848332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档