Lets say i have a ITaskRepository and a TaskEntityReposit开发者_Go百科ory that implements the ITaskRepository and wraps the access to the ObjectContext of the Entity.
public interface ITaskRepository{
Task FindById(int taskId);
void Insert(Task task);
void Update(Task task);
}
My question is now should i detach the entities from the ObjectContext when it gets returned by FindById and attach it back when the method Update is called?
Currently i don´t detach the entities from the ObjectContext, but then the Update-method contains no functionality (only calls SaveChanges())
It depends on your application.
If your working in a stateless environment (e.g ASP.NET Web Forms / MVC), then the entire context is always detached (unless your using self-tracking POCO's).
So, taking the example of an ASP.NET MVC Web Application, you've got two options when you want to make changes to an existing entity:
- Go get the entity again (using
FindById
), then useController.TryUpdateModel
to merge in the changes, then doSaveChanges()
. In this scenario, yourUpdate
method is not required. You should change it to simplySaveChanges()
. - Don't get the entity, instead use your
Update
method toAttach
the entity to the graph, and make your changes manually.
2) Is a pain with POCO's (trust me). ApplCurrentValues
only works for scalar properties, so if you want to update relationshships, you'll have to manually set the EntityState
for each relationship.
My advice - forget detaching entities, and lose your Update
method altogether.
As i said though - depends on your application.
If you do the Database design first and them create your entities from the database then there is no way to separate entities from the ObjectContext. However, you can choose the code first POCO model and then create DbContext separately, then you should be able to separate entities from the underlying context.
http://weblogs.asp.net/scottgu/archive/2010/12/08/announcing-entity-framework-code-first-ctp5-release.aspx
精彩评论