Jason King Team : Web Development Tags : Performance

Avoid unnecessary trips to the database

Jason King Team : Web Development Tags : Performance

When writing data access code please try to minimise the number of trips to the database.   Each time a query is sent to the database there is a performance overhead.   Often there is no need to perform 2 queries and 1 will do just fine.

Sometimes developers write code like this:

var blog = new Blog { Content = “New blog” };

Context.Blogs.Add(blog);

Context.SaveChanges(); // this is redundant

Context.FeaturedBlogs.Add(new FeaturedBlog { BlogId = blog.Id });

Context.SaveChanges();

There’s no need to call SaveChanges twice (and hit the database twice).   Instead just remove the first SaveChanges and rather than assigning a blogId, assign the actual blog entity.   Entity Framework will commit both inserts inside one transaction and sort everything out for you.   The code will run faster as there is only one connection to the database.

var blog = new Blog { Content = “New blog” };

Context.Blogs.Add(blog);

Context.FeaturedBlogs.Add(new FeaturedBlog { Blog = blog });

Context.SaveChanges();