LINQ to SQL - where does your DataContext live?

后端 未结 4 1888
一整个雨季
一整个雨季 2020-12-04 22:29

I\'m using LINQ to SQL in a data access object library. The library is used in both web (web application/web service) and non-web (windows service) contexts. Initially, I st

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 23:00

    The guidelines from the MSDN documentation on the DataContext class are what I would recommend following:

    In general, a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations.

    Because DataContext is IDisposable, I find it easiest to create and use a DataContext in a using statement within one method, so it can be disposed of properly.

    Also note that "any instance members are not guaranteed to be thread safe", so sharing one DataContext between multiple threads would be unwise.

提交回复
热议问题