保存多个对象

时间:2011-12-21 14:41:10

标签: entity-framework c#-4.0 repository

我有以下课程:

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; }
}

我在Save中使用TestRepository方法遇到了一些问题。

这是逻辑:

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,如果这样可以让这项工作变得更容易。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

鉴于更新的明显复杂性,将其逻辑移至存储过程然后map your updates to that stored procedure可能是有意义的。

答案 1 :(得分:1)

有两种方法可以让你这么简单,正如你所说,你想切换到经典的ADO.NET,

  1. 创建一个存储过程并将所有这些逻辑放在那里。这可以在一次Transction中完成。

  2. 使用相关的QUERY编写ADO.NET编码。

  3. 我个人更喜欢第一个选项,因为这将使用现有的实体框架。

    让我知道进一步的方向,也可以在TestRepository中使用Save方法时了解问题。

相关问题