1

在我的模型中,一个问题可以有许多有效的答案,并且一个答案可以用于许多问题。我在 Answer.Text 属性上有一个唯一索引,以防止重复并确保验证有效。我的 Seed 方法中有这段代码。

   Answer _None = new Answer { Text = "None", SortOrder = 50 };
   context.Answers.AddOrUpdate(x => x.Text, _None);
   context.SaveChanges();

   Question q = new Question 
   { 
      Text = "Bathroom flooring", 
      Answers = new Answer[] 
               {
                  _None,     
                  new Answer { Text = "Carpet", SortOrder = 60} 
               } 
   }
   context.Questions.AddOrUpdate(x => x.Text, q);
   context.SaveChanges();

该方法会引发错误,因为在第二次调用 context.SaveChanges() 时尝试另一个插入以获取文本为“None”的答案。*无法在具有唯一索引“IX_NaturalKey”的对象“dbo.Answers”中插入重复的键行*。重复键值为 (None)。”为什么在将现有对象添加到关系时会尝试第二次插入,有没有办法阻止它?

4

1 回答 1

0

你可以使用这样的东西:

context.Question.AddOrUpdate(
                p => p.Id,
                new Models.Question
                {
                    Question = "Bathroom flooring",
                    //Active = true,
                    Answers = new System.Collections.Generic.List<Answers>(){
                        new Answers {Id=1, Text = "Carpet",SortOrder=60 },
                        new Answers {Id=2, Text = "Carpet",SortOrder=60 },
            new Answers {Id=3, Text = "Carpet",SortOrder=60 },
            new Answers {Id=4, Text = "Carpet",SortOrder=60 },
            new Answers {Id=5, Text = "Carpet",SortOrder=60 },
                    }
                });
于 2013-09-06T19:47:32.440 回答