hqt
hqt

Reputation: 30266

Entity Framework 5 : Using Lazy Loading or Eager Loading

I'm sorry if my question is normal. But I meet this problem when I design my ASP.NET MVC 4.0 Application using Entity Framework 5.

If I choose Eager Loading, I just simplify using :

public Problem getProblemById(int id) {
 using(DBEntity ctx = new DBEntity ())
            {
                return (Problem) ctx.Posts.Find(id);
            }
}

But if I use Eager Loading, I will meet problem: when I want to navigate through all its attributes such as comments (of problem), User (of Problem) ... I must manually use Include to include those properties. and At sometimes, If I don't use those properties, I will lost performance, and maybe I lost the strength of Entity Framework.

If I use Lazy Loading. There are two ways to use DBContext object. First way is using DBContext object locally :

public Problem getProblemById(int id) {
 DBEntity ctx = new DBEntity ();
 return (Problem) ctx.Posts.Find(id);
}

Using this, I think will meet memory leak, because ctx will never dispose again.

Second way is make DBContext object static and use it globally :

static DBEntity ctx = new DBEntity ();
public Problem getProblemById(int id) {
 return (Problem) ctx.Posts.Find(id);
}

I read some blog, they say that, if I use this way, I must control concurrency access (because multi request sends to server) by myself, OMG. For example this link :

Entity Framework DBContext Usage

So, how can design my app, please help me figure out.

Thanks :)

Upvotes: 1

Views: 3037

Answers (1)

ken2k
ken2k

Reputation: 48965

Don't use a static DBContext object. See c# working with Entity Framework in a multi threaded server

A simple rule for ASP.Net MVC: use a DBContext instance per user request.

As for using lazy loading or not, I would say it depends, but personally I would deactivate lazy-loading. IMO it's a broken feature because there are fundamental issues with it:

  • just too hard to handle exceptions, because a SQL request can fail at any place in your code (not just in the DAL because one developer can access to a navigation property in any piece of code)
  • poor performances if not well used
  • too easy to write broken code that produces thousands of SQL requests

Upvotes: 8

Related Questions