Entity Framework Updating?
How do you update an entity in EF 4?
For example:
1) Use AutoMapper to generate the CategoryEditModel from a Category entity from the Service Layer.
2) Pass the EditModel to the View. Great!!
3) Post back the EditModel, use AutoMapper to take the CategoryEditModel --> Category.
4) Take that Category and pass it off to the Service Layer which passes it off to the Repository which in turn does an ObjectSet.Attach(TEntity开发者_Go百科).
Tells me the ObjectStateManager has another object with the same key???
I am using Ninject to inject the Controller with the Service and UnitOfWork, the Service with a Repository, the Repository with a UnitOfWork. The UnitOfWork is scoped per request.
It seems something is being held in cache maybe?
Do I have to call dispose on the UOW or will Ninject take care of it? It does implement IDisposable, and in the dispose it disposes of the context.
Entity Contexts cache objects. It's generally considered wise to keep the life of a particular context quite short. I do this by using a factory within each repository method:
public SomeObject GetSomeObjectById(int id)
{
using (var context = _contextFactory.Get())
{
return context.SomeObjects.SelectSingle(o => o.Id == id);
}
}
If you're quite certain that you want to follow the one-context-per-request model, you'll need to load the entity you want out of the context (which should be free if you use context.GetObjectByKey
because it sounds like it's cached in this case), change the values on the object, and then save changes.
I think you should use only a single Entity Framework Session object without having repository. Take a look at this post : Question about Interfaces and DI? and let me know if you have questions. It's code-first and it works perfectly for me.
Hope it helps you!
精彩评论