【发布时间】:2011-12-21 23:06:41
【问题描述】:
我有以下课程:
public class Test
{
public int Id { get; set; }
public string Title { get; set; }
public List<TestQuestion> Questions { get; set; }
}
public class TestQuestion
{
public int Id { get; set; }
public int TestId { get; set; }
public string Text { get; set; }
public List<TestQuestionAnswer> Answers { get; set; }
}
public class TestQuestionAnswer
{
public int Id { get; set; }
public int TestQuestionId { get; set; }
public string Text { get; set; }
public bool? IsCorrect { get; set; }
}
我在使用 TestRepository 中的 Save 方法时遇到了一些问题。
逻辑如下:
If Test.Id > 0 then update Test, otherwise create a new one
If TestQuestion.Id > 0 and TestQuestion.Text = "" delete TestQuestion from database and all Answers for that object
If TestQuestion.Id == 0 then create a new row in database
If TestQuestion.Id > 0 and TestQuestion.Text != "" then update that row
If TestQuestionAnswer.Id > 0 and Text = "" then delete it from database, otherwise call create or update method.
我使用的是 Entity Framework Code First,但如果这会使这项工作变得更容易,我愿意切换到经典的 ADO.NET。
任何帮助将不胜感激!
【问题讨论】:
-
为什么不清空您要删除的项目,只需删除您要删除的对象。打开级联删除,以便在您删除问题时自动删除所有答案。您正在做 EF 为您完成的大量手动工作。
-
因为这是请求的。我必须创建一个类似于 excel 表的 web 表单。如果字段为空,请将其删除,否则在数据库中创建新行或更新现有行:(
标签: entity-framework c#-4.0 repository