【问题标题】:Should I use multiple repositories in a controller or let Entity Framework do the work for me?我应该在控制器中使用多个存储库还是让实体框架为我完成工作?
【发布时间】:2014-08-07 17:23:58
【问题描述】:

理论对此有何看法?两者中哪一个是正确的方法?

让我们使用两个实体 - 一个 Question 实体和一个 Tag 实体,就像 StackOverflow 中的这里一样。假设下面的代码是控制器方法的一部分,它应该创建一个 Question 实体。请记住,问题可能有标签。所以,这个方法应该创建一个问题和它的标签(如果有的话)。

Qustion questionDbContext = new Qustion();

// Mapping the model properties to the entity's ones.
questionDbContext.Title = questionModel.Title;
questionDbContext.Body = questionModel.Body
// More mapping..
// ...
// Here Entity Framework will add all the necessary Tag and QuestionTag entities automatically.
questionDbContext.Tags = questionModel.Tags.Select(t => new Tag(t)).ToList();

this.questionsRepository.Add(questionDbContext);
this.questionsRepository.Save();

我能想到的另一种方法完全不同。

Qustion questionDbContext = new Qustion();

// Mapping the model properties to the entity's ones.
questionDbContext.Title = questionModel.Title;
questionDbContext.Body = questionModel.Body
// More mapping..
// ...

// Tag mapping
foreach(var tag in questionModel.Tags)
{
    Tag tagDbContext = new Tag();
    tagDbContext.Name = tag.Name
    // More mapping..  
    this.tagsRepository.Add(tagDbContext);
}

this.questionsRepository.Add(questionDbContext);
this.questionsRepository.Save();
this.tagsRepository.Save();

那么,哪种方法是正确的?如果两者都不是,请分享您的,谢谢:)

【问题讨论】:

  • 这就像你有额外的工作只是为了满足一个特定的模式,这很容易实现,这里是你可能需要看到的another post

标签: c# entity-framework design-patterns repository


【解决方案1】:

首先,我认为这比 SO 更适合放在代码审查中。但是要回答您的问题,根据我的轶事经验,差异确实很小。我会说选择最容易使用的那个,然后阅读。在这点上,我个人会选择第一个。

旁注:如果你确实想走 foreach() 路线,并且速度是主要因素,我会改为使用普通的 for 循环

for(int i=0;i<QuestionModel.Tags;i++){...}

因为简单的 for 循环比 foreach 循环快。无论如何,我仍然会强调可读性而不是小的性能提升。

【讨论】:

    猜你喜欢
    • 2011-07-19
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 2013-03-27
    • 2015-04-03
    相关资源
    最近更新 更多