should EF dbContext be created on every transaction

*爱你&永不变心* 提交于 2020-01-13 19:22:51

问题


I'm trying to figure out the best way to manage the DbContext. I've seen code samples that don't dispose and I've seen people say that that is a bad idea. Is it appropriate for me to do something like below? Also, should I put every transaction, including reads, in a new DbContext? This might be another question, but is the part about the EntityState necessary?

public abstract class GenericRepository<T> where T : EntityData
{
    protected MyDbContext Context
    {
        get { return new MyDbContext(); }
    }

    public T Save(T obj)
    {
        T item;
        using (var context = Context)
        {
            var set = context.Set<T>();

            if (String.IsNullOrEmpty(obj.Id))
                item = set.Add(obj);
            else
            {
                item = set.Find(obj.Id);
                item = obj;
            }

            // taken from another code sample
            var entry = context.Entry(item);
            if (entry.State == EntityState.Detached)
            {
                //Need to set modified so any detached entities are updated 
                // otherwise they won't be sent across to the db. 
                // Since it would've been outside the context, change tracking 
                //wouldn't have occurred anyways so we have no idea about its state - save it!
                set.Attach(item);
                context.Entry(item).State = EntityState.Modified;
            }
            context.SaveChanges();
        }

        return item;
    }
}

EDIT
I also have an extended class that implements this function below. The context is not being wrapped in a using statement in this query, so I'm a little suspicious of my code.

public IQueryable<T> FindByAccountId(string accountId)
{
    return from item in Context.Set<T>()
        let user = UserRepository.FindByAccountId(accountId).FirstOrDefault() 
        where item.UserId == user.Id
        select item;
}

回答1:


Contexts should really be on a per request basis. The request comes in and a new context is created. This context is used for the remainder of the request then disposed of at the end of the request accordingly. This gives you the benefit of request long transactions, and as highlighted by HamidP, you also have the added benefit of cached entities; meaning that any entities loaded into the context can be loaded by retrieved without Entity Framework needing to query the database.

If you're using any kind of inversion of control container such as StructureMap then you can easily create HTTP request bound contexts by a configuration such as:

this.For<DbContext>().HybridHttpOrThreadLocalScoped().Use<DbContext>();

You're then able to inject your DbContext (or a derivative of it) into your repository and leave your IOC container of choice to dispose of the context at the end of the request. If you were to inject the same context into another repository then you'd receive the same instance of the context.

I hope this helps!




回答2:


No, it should not

Best approach here is to assign a context just for a request. you should attach a context to an incoming request and dispose your context when request is finished. In this approach you save the overhead of creating a context for every transaction and also benefit from caching mechanism of context because each context has it's inside cache and a request may access the data it had access recently.

Creating a context for each transaction is not as bad as having a long life context!! Don't ever do that, long life contexts result in many concurrency issue and the cache becomes stale and memory consumption grows high and higher and you should maintain your application in future by miracles.



来源:https://stackoverflow.com/questions/26923462/should-ef-dbcontext-be-created-on-every-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!