正在尝试从父对象中删除多个深子对象。
树是这样的:
Survey.SectionList.Section.QuestionList.Question.QuestionType
我希望是这样的:
Survey.SectionList.Section.QuestionList.Question
我正在从由系统的其他实例导出的XML文件导入测量对象。导出的一部分是QuestionType。当我导入调查并将其推入到一个测量对象中,然后使用db.Add跟随它时,将添加QuestionType记录,而不仅仅是引用现有记录。
(我想)我知道我可以把它全部放在一系列foreach循环中,以深入到问题层,但这似乎太老套了。
提前感谢你对这颗幼小的心的耐心。
发布于 2015-02-11 05:25:27
你可以得到所有的问题,然后修改它们:
给定:List<Survey> surveyList
List<Question> questions = surveyList.SelectMany(s => s.SectionList)
.SelectMany(sl => sl.Section)
.SelectMany(sct => sct.QuestionList)
.SelectMany(ql => ql.Question).ToList();
foreach(Question q in questions)
q.QuestionType = null;或者,您可以通过使用"linq-to-objects更新“来获得更多的乐趣:
surveyList.SelectMany(s => s.SectionList)
.SelectMany(sl => sl.Section)
.SelectMany(sct => sct.QuestionList)
.SelectMany(ql => ql.Question)
.Select(q =>
{
q.QuestionType = null;
return q;
}).ToList();发布于 2015-02-11 06:09:08
您可以覆盖DbContext类中的SaveChanges,并将QuestionType对象的状态设置为UnChanged
public override int SaveChanges()
{
var oc = ((IObjectContextAdapter)this).ObjectContext;
oc.DetectChanges();
foreach (var ent in oc.ObjectStateManager
.GetObjectStateEntries(EntityState.Added)
.Select(e => e.Entity)
.OfType<QuestionType>())
{
oc.ObjectStateManager.ChangeObjectState(ent, EntityState.Unchanged);
}
return base.SaveChanges();
}通过将状态设置为UnChanged,Question和QuestionType之间的关联将保持不变,但现在只保存外键值,而不保存QuestionType。
发布于 2015-02-12 02:57:51
你们太棒了。谢谢你在我那差劲的帖子里给出了各种各样的真实答案。
这就是我昨天终于开始工作的原因,这样我就可以继续前进了。但是,在我添加了单元测试之后,我将重构您的一个响应。
private Survey PrepSurveyForAdd(Survey survey)
{
//Loop through the sections
foreach (SurveySection ss in survey.SurveySections)
{
foreach (SectionQuestion sq in ss.Section.SectionQuestions)
{
sq.Question.QuestionType = null;
}
}
return survey;
}我没有坚持下去的原因,以及我最初发帖的原因,是因为我不仅在向下引用这棵树时遇到了问题,而且因为我想在现实世界中学习更多关于Linq的知识,这对我来说很重要。
https://stackoverflow.com/questions/28441599
复制相似问题