开发者

Detaching entities when using RepositoryPattern with EntityFramework

开发者 https://www.devze.com 2023-02-08 06:49 出处:网络
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.

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:

  1. Go get the entity again (using FindById), then use Controller.TryUpdateModel to merge in the changes, then do SaveChanges(). In this scenario, your Update method is not required. You should change it to simply SaveChanges().
  2. Don't get the entity, instead use your Update method to Attach 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

0

精彩评论

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