2

I have a simple model containing two entities:

  • Post entity - an aggregate root, which can have a list of Comment -> Comments
  • Comment entity

When adding a new comment, lets say it's this:

post.Comments.Add(newComment);

System will request a SELECT to load all existing comments before adding the new one. But if there are hundreds of comments so it's heavy right. Is it possible to avoid the load? Thanks for any suggestion.

fred
  • 693
  • 1
  • 7
  • 19

2 Answers2

2

This is a classic problem with ORMs. There is no silver bullet here.

If you load all the comments in advance you're causing a lot of bandwidth wasted since all the comments might not be needed.

On the other hand, if you don't load the comments in advance and someone does something like:

for(var i = 0; i < 100; i++){
     doSomethingWith(post.Comments[i]); 
}

You're causing a hundred fetches from the database - effectively causing the Select n+1 issue.

So, it's an opinionated design choice, some ORMs will only fetch the post, others will include special syntax like .Include which indicates you're also interested in the comments and some will ignore this completely and waste requests.

Community
  • 1
  • 1
Bimper
  • 270
  • 1
  • 8
1

You're concerned about performance of inserting a new comment, so maybe below options can help:

  1. Reuse the db connection from nhibernate, write your own insert command
  2. With support of Dapper, write your insert query https://github.com/StackExchange/dapper-dot-net
hazjack
  • 1,645
  • 13
  • 27