1

I know that it's not a good practice to keep a DataContext alive and re-use it, so I wrapped it in a Using statement.

Also, as far as I know, DataContext opens a connection when it's being initialized, and closes the connection when it's disposed.

What I'm looking to accomplish here, is keeping a separate connection open for each currently logged in user (and close the connection manually when the user logs out).

Multithreading is not an issue, because I'm using locks.

I keep SQLConnections and pass them to the DataContext constructor. This sort of works. But the problem is that DataContext automatically closes the connection when it's disposed.

Is it somehow possible to force the DataContext to not close the connection it uses?

4

1 回答 1

2

一般来说,如果您尝试在记录中执行某种循环,并且DataContext每次都创建一个(并且,通过扩展,一个 SQL 连接),您的痛点就会出现。只要你不这样做,你就不应该有任何重大的性能问题。

在我看来,保持 SQL 连接打开以便您可以将其传递给 DataContext 的概念是过早的优化。SQL 连接并没有那么昂贵,DataContext对象也没有。

通常,DataContext对象的生命周期应该与关联的 Repository 对象的生命周期相同。

例子

public class CustomerRepository
{
    private MyDatabaseDataContext dataContext;

    public CustomerRepository()
    {
        dataContext = new MyDatabaseDataContext();
    }

    public Customer GetCustomer(int id)
    {
        return dataContext.Customers.FirstOrDefault(x => x.id == id);
    }

    public IQueryable<Customer> CustomersByRep(int repID)
    {
        return dataContext.Customers.Where(x => x.repID == repID);
    }
}

另请参阅
ASP.NET MVC 技巧 #34 – 处理您的 DataContext(或不处理)

于 2012-06-04T22:10:04.537 回答