LinqToSql static DataContext in a web application

后端 未结 5 1105
囚心锁ツ
囚心锁ツ 2021-01-02 12:14

In a web application that I have run across, I found the following code to deal with the DataContext when dealing with LinqToSQL

public partial class DbDataC         


        
相关标签:
5条回答
  • 2021-01-02 12:33

    I have done many Linq to Sql web apps and I am not sure if what you have would work.

    The datacontext is supposed to track the changes you make to your objects and it will not do that in this instance.

    So when you go hit submit changes, it will not know that any of your objects where updated, thus not update the database.

    You have to do some extra work with the datacontext in a disconnected environment like a web application. It is hardest with an update, but not really that bad. I would not cache and just recreate it.

    0 讨论(0)
  • 2021-01-02 12:36

    A DataContext is cheap to make and you won't gain much by caching it in this way.

    0 讨论(0)
  • 2021-01-02 12:37

    Also the context itself is not transactional so it is theoretically possible an update could occur on another request and your update could fail.

    0 讨论(0)
  • 2021-01-02 12:41

    This is not a static copy. Note that the property retrieves it from Context.Items, which is per-request. This is a per-request copy of the DataContext, accessed through a static property.

    On the other hand, this property is assuming only a single thread per request, which may not be true forever.

    0 讨论(0)
  • 2021-01-02 12:48

    I prefer to create a Page base class (inherit from System.Web.UI.Page), and expose a DataContext property. It ensures that there is one instance of DataContext per page request.

    This has worked well for me, it's a good balance IMHO. You can just call DataContext.SubmitChanges() at the end of the page and be assured that everything is updated. You also ensure that all the changes are for one user at a time.

    Doing this via static will cause pain -- I fear DataContext will lose track of changes since it's trying to track changes for many users concurrently. I don't think it was designed for that.

    0 讨论(0)
提交回复
热议问题