开发者

Performance effects with instances of entities in EntityFramework

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜