在层之间传递实体对象的正确方法? [英] Correct way to pass Entity objects between layers?

查看:148
本文介绍了在层之间传递实体对象的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习实体框架,并将其与分层代码结构相结合,取得了一些进展。我有2个视觉层,一个业务层和一个数据访问层。

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

我收到错误消息 ObjectContext实例已经被处理,不能再用于需要连接的操作。

如果我从GetActiveUsers中删除使用方法,它工作正常。

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

我知道这是危险的做法,因为GC可以在任何给定的时间处理上下文,并拧紧我的BLL。

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?

推荐答案

因为您正在从 IQueryable DAL,您不能使用使用语句。

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

查询是延迟直到触发查询 - .ToList 在您的BLL中。

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

到那时,上下文被处理。

By that time, the context is disposed.

认真思考关于使用IQueryable,因为在没有了解所有细节的情况下,这是冒险的做法。

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

由于你还在学习EF,我会保持很简单:

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

这篇关于在层之间传递实体对象的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆