Correct way to pass Entity objects between layers?

断了今生、忘了曾经 提交于 2019-12-05 20:56:23

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