简体   繁体   中英

Managing DbContext EF6

I'm building a Webforms EF6 database first application and am not sure how best to manage DbContext. I looked at a lot of tutorials and forum posts but I'm still sure. Regarding the much favored 'using per request', I've not found a way to save parent & children in one go. I got it to work with the code below, but where and when would I dispose of the context? Can I use this approach? Would the per request approach by Kamyar shown here be better?

Here's what I've got now:

public static class ContextManager
{
    [ThreadStatic]
    private static MyContext current;

    public static MyContext MyCurrentContext
    {
        get{
        if (current == null)
            current = new MyContext();

        return current;
    }}
}

coupled with

var context = ContextManager.MyCurrentContext;
.....
context.SaveChanges();

Thanks in advance for any help!

A specific example would be 'UserProfile' which contains child objects as properties such as 'DefaultInvoiceAddress' which returns the user's default invoice address from a table with all the user's addresses. In the last web application I worked on, when user edits this address from within the profile (eg street change), together with other profile information from other tables, EF would save all edited information from the different tables in one request (ensuring they're attached). Since I wasn't privy to the context management, I don't know how it was done, but we would always assign a common current context for the requests.

I came across this post by Rick Strahl , and this one by Jordan van Gogh - the business object / transaction seem to be an answer, but I don't quite understand how to implement it and couldn't find an example. The 'shared ObjectContext instance per HTTP request' corresponds to Kamyar's answer mentioned above, and all things considered, it sounds a good option. Would I have to explicitly dispose of the context, if so when/where?. Are there any drawbacks?

Bad idea. Static is totally against the best practices. No 2 users ever will use the app at the same time? Ouch. For WebForms.

Per request IS the best choice.

The EF db context object is not , I repeat NOT threadsafe no matter how you manage it. Lots of problems can arise from sharing a db context across threads so the best way is, as mentioned above to use it per request.

If you don't want to jump into the IoC/DI side of things a really simple way to do it is whenever you need the database you just instantiate your context in a using block, like so:

using(var db = new MyContext())
{
    // code reading from/writing to database
    ...
    ...
}

在实体框架数据库上下文中使用单例模式是一个设计缺陷,特别是在处理诸如Web表单之类的并发环境时,因为必须考虑DbContext不是线程安全的对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM