1

It is an MVC application with Entity Framework Code First for the ORM and MEF as the IoC. If I mark the DbContext with PartCreationPolicy.Shared there is an error saying the object already exists in the container every time I try to perform an edit. But what if I simply mark the DbContext with PartCreationPolicy.NonShared so it gets created for every request? Is there a terrible performance impact for that?

Update Here is the code for save:

Provider IRepository<Provider>.Put(Provider item)
        {
            if (item.Id == Guid.Empty)
            {
                item.Id = Guid.NewGuid();
                this.Providers.Add(item);
            }
            else this.Entry<Provider>(item).State = EntityState.Modified;
            return item;
        }

And this is the error when on Shared

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

Vahid
  • 257
  • 4
  • 14
  • I just posted the code and the error message. – Vahid Apr 06 '13 at 14:46
  • I think the problem is related to your multiple objects with the same key in `Provider` table – Bhushan Firake Apr 06 '13 at 14:46
  • @BhushanFirake That's not possible, Code First using the `[Key]` attribute will form the primary key, which will **never** allow duplicates. – Mathew Thompson Apr 06 '13 at 14:48
  • @BhushanFirake The problem is that when I first loaded the object for display EF put it in its state manager thing and when I'm trying to save the edited object that previously loaded object causes the conflict since while in `Shared` it maintains the container. – Vahid Apr 06 '13 at 14:51
  • 2
    New creation of the context for every request is the correct approach. The performance impact is practically zero. – Slauma Apr 06 '13 at 14:55

1 Answers1

3

You should definitely use PartCreationPolicy.NonShared. Everything you can read about context lifecycle management, whether it's linq to sql, entity framework, or NHibernate (sessions), will agree upon one thing: the context should be short-lived. An easy rule of the thumb is: use it for one unit of work, which means: create a context, do stuff, call SaveChanges once, dispose. Most of the times this rule works well for me.

A shared (or singleton) context is the pattern that hits performance, because the context gets bloated over time. The change tracker needs to track more and more objects, relationship fixup will get slower. And you will find yourself refreshing (re-loading) entities time and again.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291