Search code examples
entity-framework-4idisposableobjectcontext

Correct way to pass Entity objects between layers?


I am just learning the Entity Framework and have made some good progress on incorporating it with my layered code structure. I have 2 visual layers, a business layer and a data access layer.

My problem is in passing entity object between layers. This code sample does not work:

// BLL
public static void Test1()
{
 List<User> users = (from u in GetActiveUsers()
      where u.ID == 1
      select u).ToList<User>();

 // Do something with users
}

// DAL
public static IQueryable<User> GetActiveUsers()
{
 using (var context = new CSEntities())
 {
  return from u in context.Users
      where u.Employee.FirstName == "Tom"
      select u;
 }
}

I get the error message The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

If I remove the using from the GetActiveUsers method, it works fine.

I know this is dangerous practice as the GC can dispose of the context at any given time and screw up my BLL.

So, what is the correct way to pass information between layers? Do I need to pass the context around as well?


Solution

  • Because you are returning IQueryable from your DAL, you cannot use the using statement.

    The query is deferred until to are firing the query - .ToList in your BLL.

    By that time, the context is disposed.

    Think carefully about using IQueryable, as it is risky practice without knowing all the details.

    Since you are still learning EF, i would keep it simple:

    // BLL
    public static void Test1()
    {
     List<User> users = GetActiveUsers();
     var singleUser = users.SingleOrDefault(u => u.ID == 1);
    
     // Do something with users
    }
    
    // DAL
    public static ICollection<User> GetActiveUsers()
    {
     using (var context = new CSEntities())
     {
      var users = from u in context.Users
          where u.Employee.FirstName == "Tom"
          select u;
      return users.ToList();
     }
    }
    

    If you want to get a single user, create another method:

    // DAL
    public static User GetSingleActiveUser(int userId)
    {
     using (var context = new CSEntities())
     {
      var users = from u in context.Users
          where u.Employee.UserId == userId
          select u;
      return users.SingleOrDefault();
     }
    }