开发者

Performance effects with instances of entities in EntityFramework

开发者 https://www.devze.com 2023-02-09 10:59 出处:网络
What behavior should I use for a provider pattern with entity framewo开发者_开发知识库rk? public class TestProvider : IDisposable

What behavior should I use for a provider pattern with entity framewo开发者_开发知识库rk?

public class TestProvider : IDisposable
{
    public Entities entities = new Entities();

    public IEnumerable<Tag> GetAll()
    {
        return entities.Tag.ToList();
    }

    public ...

    #region IDisposable Members

    public void Dispose()
    {
        entities.Dispose();
    }

    #endregion
}

Or is it ok to use:

public class TestProvider
{
    public IEnumerable<Tag> GetAll()
    {
        using (var entities = new Entities())
        {
            return entities.Tag.ToList();
        }
    }

    public ...
}

Does it implies on performance? What are the pros and cons about it?


It depends on how long should TestProvider exist and what operations do you want to perform on retrieved entities. Generally ObjectContext instance should be used for the shortest time as possible but it should also represent single unit of work. ObjectContext instance should not be shared. I answered related question here.

It means that both your approaches are correct for some scenarios. First approach is ok if you expect to retrieve entities, modify them and the save them with the same provider instance. Second approach is ok if you just want to retrieve entities, you don't want to immediately modify them and you don't want to select anything else.

0

精彩评论

暂无评论...
验证码 换一张
取 消