0

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 :)

Yulian
  • 6,262
  • 10
  • 65
  • 92
  • It's like you have extra work just to satisfy a specific pattern, that can be achieved easily, here is [another post](http://stackoverflow.com/questions/14110890/not-using-repository-pattern-use-the-orm-as-is-ef) that you might need to see – Yuliam Chandra Aug 07 '14 at 17:34

1 Answers1

0

First I think this is better placed in code review, rather than SO. But to answer your question, In my anecdotal experience, the difference is really small. I would say go for whichever is easiest for you to use, and read. On that note I would personally go for the first.

Side Note: if you do want to go the foreach() route, and speed is a primary factor, I would instead use a normal for loop

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

As the simple for loop is faster than a foreach loop. Ether way I would still air towards readability than small performance gains.

Mr. MonoChrome
  • 1,383
  • 3
  • 17
  • 39