【问题标题】:Saving multiple objects保存多个对象
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 感谢您的回答!存储过程完全可以,但是我在编写 SP 方面经验很少。你能给我一个“复杂”对象层次结构 Test/TestQuestion/TestQuestionAnswer 的样本吗?
【解决方案2】:

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

  1. 创建一个存储过程并将所有这些逻辑放在其中。这可以在单个事务中完成。

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

我个人更喜欢第一个选项,因为它会利用现有的实体框架。

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

【讨论】:

  • 我想使用存储过程并在单个事务中进行 CRUD。我必须为每个实体编写 3 个 CRUD 存储过程,还是只创建一个?在这种情况下,我必须创建一个新的用户定义表类型并将其设置为我的 SP 中的输入参数,对吧?
猜你喜欢
  • 2014-11-23
  • 2021-01-10
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多