实体框架:使用现有数据(种子)填充多对多关系
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实体框架:使用现有数据(种子)填充多对多关系相关的知识,希望对你有一定的参考价值。
在我的Code-First数据库中,我在对象“Question”和对象“Section”之间存在多对多关系,如下所示:在Section:
public List<Question> Questions { get; set; }
问题:
public List<Section> Sections { get; set; }
这确实在两者之间创建了一个名为QuestionSections的链接表。但是,当我尝试运行我的种子方法时,链接表不会被填充。
种子方法代码的相关部分如下:
var Sections = new List<Section>
{
new Section
{
InternalSectionId = 1,
Name = "Global information",
SurveyId = context.Surveys.First(s => s.Title == "Test Survey").Id
},
new Section
{
InternalSectionId = 2,
Name = "More specific",
SurveyId = context.Surveys.First(s => s.Title == "Test Survey").Id
},
new Section
{
InternalSectionId = 3,
Name = "TestingSection",
SurveyId = context.Surveys.First(s => s.Title == "Test Survey").Id
}
};
Sections.ForEach(x => context.Sections.AddOrUpdate(ss => ss.Name, x));
context.SaveChanges();
List<Section> section1 = context.Sections.Where(sect => sect.InternalSectionId == 1 && sect.SurveyId == 1)
.ToList();
List<Section> section2 = context.Sections.Where(sect => sect.InternalSectionId == 2 && sect.SurveyId == 1)
.ToList();
List<Section> section3 = context.Sections.Where(sect => sect.InternalSectionId == 3 && sect.SurveyId == 1)
.ToList();
var questions = new List<Question>
{
new Question
{
Sections = section1,
Title = "What is 1+1?",
QuestionOrderId = 1,
AnswerRequired = true,
InputTypeId = context.InputTypes.First(ip => ip.VisibleName.Equals("Dropdownbox")).Id,
StorageType = (int)Constants.Constants.StorageTypes.BoolType
},
new Question
{
Sections = section2,
Title = "What is 2/1?",
QuestionOrderId = 1,
AnswerRequired = true,
InputTypeId = context.InputTypes.First(ip => ip.VisibleName.Equals("Text")).Id,
StorageType = (int)Constants.Constants.StorageTypes.IntType
}
}
}
questions.ForEach(x => context.Questions.AddOrUpdate(q => q.Title, x));
context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();
创建问题,创建部分,但不填充链接表。我已经检查了对象section1,section2和section3是否已启动并填充,它们是。
我究竟做错了什么?
答案
您还必须将类似的代码写入Link表。 questions.ForEach(x => context.Questions.AddOrUpdate(q => q.Title, x));
因为当你调用context.SaveChanges();
时DBContext不知道这个链接表。
以上是关于实体框架:使用现有数据(种子)填充多对多关系的主要内容,如果未能解决你的问题,请参考以下文章