4

What behavior should I use for a provider pattern with entity framework?

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?

Edwin Jarvis
  • 5,430
  • 6
  • 33
  • 41
BrunoLM
  • 88,362
  • 76
  • 272
  • 427

1 Answers1

1

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.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654