【发布时间】: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