What does the theory say about this? Which of the two is the right approach?
Let's take two entities - a Question entity and a Tag one, just like here in StackOverflow. Assume that the code below is part from a controller's method supposed to create a Question entity. Remember that a Question may have Tags. So, this method should create both - a Question and its Tags (if there are any).
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();
The other approach I can think of is quite different.
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();
So, which approach is right? If neither of them, share yours, thank you :)