Correct way to pass Entity objects between layers?

二次信任 提交于 2019-12-07 18:08:31

问题


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?


回答1:


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();
 }
}


来源:https://stackoverflow.com/questions/4101502/correct-way-to-pass-entity-objects-between-layers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!