加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 关于在Linq中重用db上下文的意见

发布时间:2020-12-15 08:29:44 所属栏目:百科 来源:网络整理
导读:我有一个使用 linq访问数据库的类.一些方法称其他方法.例如: class UserManager{ public User[] getList() { using(var db = new MyContext()) { return db.Users.Where(item = item.Active == false); } } public User[] addUser(string name) { using(var
我有一个使用 linq访问数据库的类.一些方法称其他方法.例如:
class UserManager
{
   public User[] getList()
   {
       using(var db = new MyContext())
       {
             return db.Users.Where(item => item.Active == false);
       }
    }
    public User[] addUser(string name)
    {
       using(var db = new MyContext())
       {
           db.Users.InsertOnSubmit(new User() { id = Guid.NewId(),name = name,active = false ...});
       }
       return getList();
    }

在对addUser的调用中,我需要返回新列表. (我知道它不是很好的设计,但为了简单起见,我已经删除了细节.)但是,对getList的调用会创建第二个数据上下文.

我可以用额外的方法填写这个,即:

public getList()
{
     using(var db = new MyContext())
        return getList(db);
}
public getList(MyContext db)
{
      ...
}

然后在addUser中替换我的调用,以保持相同的数据上下文.

我似乎在我的代码中看到了很多类型的东西,我担心创建和释放所有这些数据上下文的成本.有没有人对是否值得投入额外的工作以消除这些背景的创建和删除有意见?

解决方法

Microsoft提供以下建议/建议,以避免重用DataContext实例 http://msdn.microsoft.com/en-us/library/bb386929.aspx

常见问题(LINQ to SQL)

Connection Pooling

Q. Is there a construct that can help
with DataContext pooling?

A. Do not try to reuse instances of
DataContext.
Each DataContext
maintains state (including an identity
cache) for one particular edit/query
session. To obtain new instances based
on the current state of the database,
use a new DataContext.

You can still use underlying ADO.NET connection pooling. For more information,see SQL Server Connection Pooling (ADO.NET).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读