Correct way to transfer Entity objects between layers?

I am just exploring the Entity Framework and have achieved some success in integrating it with my layered code structure. I have two visual layers, a business layer and a data access layer.

My problem is passing the object of the object between the layers. This sample code 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 an error An instance of ObjectContext has been deleted and can no longer be used for operations that require a connection.

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

I know this is a dangerous practice, as the GC can get rid of the context at any given time and ruin my BLL.

So what is the correct way to transfer information between layers? Do I need to convey context as well?

+3
1

IQueryable DAL, .

, - .ToList BLL.

.

IQueryable, , .

EF, :

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

, :

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

Source: https://habr.com/ru/post/1773136/


All Articles