实体框架 4 - 在哪里放置“ApplyCurrentValues”逻辑?

发布于 2024-10-03 02:51:27 字数 1944 浏览 3 评论 0原文

我正在使用“存根技术”来更新我的 POCO(在分离上下文中使用,ASP.NET MVC)。

这是我当前在控制器中的代码(可以工作):

[HttpPost]
public ActionResult Edit(Review review)
{
   Review originalReview = _userContentService.FindById(review.PostId) as Review;
   var ctx = _unitOfWork as MySqlServerObjectContext;
   ctx.ApplyCurrentValues("MyEntities.Posts", review);
   _unitOfWork.Commit();
   // ..snip - MVC stuff..
}

如您所见,到处都有代码味道。 :)

几点:

  1. 我基本上对所有事情都使用依赖注入(基于接口)
  2. 我使用工作单元模式来抽象 ObjectContext 并提供跨多个存储库的持久性
  3. 目前我的 IUnitOfWork 接口只有 1 个方法: void Commit();
  4. 控制器通过 DI IUserContentService 调用
  5. Find 注入 IUserContentServiceIUnitOfWork > 在存储库中,它使用 ObjectContext

我不喜欢上述代码中的两件事:

  1. 我不想将 IUnitOfWork 转换为 MySqlServerObjectContext
  2. 我不希望控制器必须关心 ApplyCurrentValues

我基本上希望我的代码如下所示:

[HttpPost]
public ActionResult Edit(Review review)
{
   _userContentService.Update(review);
   _unitOfWork.Commit();
   // ..snip - MVC stuff..
}

有什么想法可以做到这一点吗? (或类似的东西)。

我已经聪明地根据类型(泛型组合、复数形式)计算出实体集名称,所以不用太担心。

我想知道放置 ApplyCurrentValues 的最佳位置在哪里?将其放入 IUnitOfWork 接口中似乎并不合适,因为这是一个持久性 (EF) 问题。出于同样的原因,它不属于服务。如果我把它放在我的 MySqlServerObjectContext 类中(有意义),我会从哪里调用它,因为没有任何东西可以直接访问这个类 - 当有东西请求 IUnitOfWork 时,它是通过 DI 注入的代码>.

有什么想法吗?

编辑

我有一个使用存根技术的解决方案,但问题是如果我事先检索了要更新的实体,它会抛出异常,说明具有该键的实体已经存在。

这是有道理的,尽管我不确定如何解决这个问题?

我是否需要“检查实体是否已附加,如果没有,则附加它?”

有 EF4 专家可以提供帮助吗?

编辑

没关系 - 找到了解决方案,请参阅下面的答案。

I'm using the "stub technique" to update my POCO's (used in a detached context, ASP.NET MVC).

This is the code i currently have in my controller (which works):

[HttpPost]
public ActionResult Edit(Review review)
{
   Review originalReview = _userContentService.FindById(review.PostId) as Review;
   var ctx = _unitOfWork as MySqlServerObjectContext;
   ctx.ApplyCurrentValues("MyEntities.Posts", review);
   _unitOfWork.Commit();
   // ..snip - MVC stuff..
}

As you can see, there is code smell everywhere. :)

A few points:

  1. I use Dependency Injection (interface-based) for basically everything
  2. I use the Unit of Work pattern to abstract ObjectContext and provide persistence across multiple repositories
  3. Currently my IUnitOfWork interface has only 1 method: void Commit();
  4. Controller have IUserContentService and IUnitOfWork inject by DI
  5. IUserContentService calls Find in Repositories, which use the ObjectContext.

These are two things i don't like with my above code:

  1. I don't want to cast the IUnitOfWork as MySqlServerObjectContext.
  2. I don't want the Controller to have to care about ApplyCurrentValues

I basically want my code to look like this:

[HttpPost]
public ActionResult Edit(Review review)
{
   _userContentService.Update(review);
   _unitOfWork.Commit();
   // ..snip - MVC stuff..
}

Any ideas how i can do that? (or something similar).

I already have smarts to work out the entity set name based on the type (combination of generics, pluralization), so don't worry too much about that.

But i'm wondering where the best place to put ApplyCurrentValues is? It doesn't seem appropriate to put it in the IUnitOfWork interface, as this is a persistence (EF) concern. For the same reason it doesn't belong in the Service. If i put it in my MySqlServerObjectContext class (makes sense), where would i call this from, as nothing directly has access to this class - it is injected via DI when something requests IUnitOfWork.

Any thoughts?

EDIT

I have a solution below using the stub technique, but the problem is if i had retrieved the entity i am updating beforehand, it throws an exception, stating an entity with that key already exists.

Which makes sense, although i'm not sure how can resolve this?

Do i need to "check if the entity is already attached, if not, attach it?"

Can any EF4 experts out there help?

EDIT

Nevermind - found the solution, see answer below.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生生漫 2024-10-10 02:51:27

想通了 - 并不容易,所以我会尽力解释。 (对于那些关心的人)

控制器相关代码:

// _userContentService is IUserContentService
_userContentService.Update(review);

因此,我的控制器在 IUserContentService 上调用一个名为 Update 的方法,传递强类型 <代码>查看对象。

用户内容服务相关代码

public void Update(Post post)
{
   // _userContentRepository is IPostRepository
   _userContentRepository.UpdateModel(post);
}

因此,我的服务调用 IPostRepository 上名为 UpdateModel 的方法,并传递强类型 Review对象。

现在,这是棘手的部分。

我实际上没有特定的存储库。我有一个名为 GenericRepository通用存储库 :IRepository,它处理所有不同的存储库。

因此,当有东西请求IPostRepository(我的服务正在做的)时,DI会给它一个GenericRepository

但现在,我给它一个 PostRepository

public class PostRepository : GenericRepository<Post>, IPostRepository
{
   public void UpdateModel(Post post)
   {
      var originalPost = CurrentEntitySet.SingleOrDefault(p => p.PostId == post.PostId);
      Context.ApplyCurrentValues(GetEntityName<Post>(), post);
   }
}

并且因为该类派生GenericRepository,它继承了所有核心存储库逻辑(查找、添加、 ETC)。

起初,我尝试将 UpdateModel 代码放入 GenericRepository 类本身中(然后我就不需要这个特定的存储库),但问题是逻辑检索现有实体是基于特定的实体键,而 GenericRepository不会知道该实体键。

但最终的结果是缝合隐藏在数据层的深处,我最终得到了一个非常干净的控制器。

编辑

这种“存根技术”也有效:

public void UpdateModel(Post post)
{
   var stub = new Review {PostId = post.PostId};
   CurrentEntitySet.Attach(stub);
   Context.ApplyCurrentValues(GetEntityName<Post>(), post);
}

但问题是因为 Post 是抽象的,我无法实例化,因此必须检查 Post 的类型并为 创建存根em>每一个派生类型。不是一个真正的选择。

编辑2(上次)

好的,使用了抽象类的“存根技术”,所以现在并发问题已经解决了。

我向 UpdateModel 方法添加了一个通用类型参数,以及特殊的 new() 约束

实现:

public void UpdateModel<T>(T post) where T : Post, new()
{
   var stub = new T { PostId = post.PostId };
   CurrentEntitySet.Attach(stub);
   Context.ApplyCurrentValues(GetEntityName<Post>, post);
}

接口:

void UpdateModel<T>(T post) where T : Post, new();

这使我不必手动找出 T 的类型,防止并发问题,也防止额外访问数据库。

相当时髦。

编辑3(我认为最后一次是最后一次)

上面的“存根技术”有效,但是如果我事先检索对象,它会抛出一个异常,说明具有该键的实体已存在于OSM。

谁能建议如何处理这个问题?

编辑4(好的 - 就是这样!)

我找到了解决方案,感谢这个答案:可以检查对象是否已附加到数据上下文实体框架?

我曾尝试使用以下代码“检查实体是否已附加”:

ObjectStateEntry entry;
CurrentContext.ObjectStateManager.TryGetObjectStateEntry(entity, out entry);

但它总是返回null,即使当我探索OSM时我也可以在那里看到我的实体用同一把钥匙。

但这段代码有效:

CurrentContext.ObjectStateManager.TryGetObjectStateEntry(CurrentContext.CreateEntityKey(CurrentContext.GetEntityName<T>(), entity), out entry)

也许因为我使用的是 Pure POCO,OSM 无法计算出实体密钥,谁知道呢。

哦,我添加的另一件事 - 这样我就不必为每个实体添加特定的存储库,我创建了一个名为“[EntityKey]”的属性(公共属性属性)。

所有 POCO 必须有 1 个用该属性装饰的公共属性,否则我会在存储库模块中抛出异常。

因此,我的通用存储库会查找此属性以创建/设置存根。

是的 - 它使用反射,但它是聪明的反射(基于属性),并且我已经使用反射来对 T 中的实体集名称进行复数化。

无论如何,问题已解决 - 现在一切正常!

Figured it out - wasn't easy, so i'll try to explain best i can. (for those who care)

Controller Relevant Code:

// _userContentService is IUserContentService
_userContentService.Update(review);

So, my controller calls a method called Update on IUserContentService, passing through the strongly-typed Review object.

User Content Service Relevant Code

public void Update(Post post)
{
   // _userContentRepository is IPostRepository
   _userContentRepository.UpdateModel(post);
}

So, my service calls a method called UpdateModel on IPostRepository, passing through the strongly-typed Review object.

Now, here is the tricky part.

I actually have no specific Repositories. I have a generic repository called GenericRepository<T> : IRepository<T>, which handles all the different repositories.

So when something requests a IPostRepository (which my service was doing), DI would give it a GenericRepository<Post>.

But now, i give it a PostRepository:

public class PostRepository : GenericRepository<Post>, IPostRepository
{
   public void UpdateModel(Post post)
   {
      var originalPost = CurrentEntitySet.SingleOrDefault(p => p.PostId == post.PostId);
      Context.ApplyCurrentValues(GetEntityName<Post>(), post);
   }
}

And because the class derives from GenericRepository, it inherits all the core repository logic (Find, Add, etc).

At first, i tried to put that UpdateModel code in the GenericRepository class itself (and then i wouldn't have needed this specific repository), but the problem is the logic to retrieve the existing entity is based on a specific entity key, which the GenericRepository<T> would not know about.

But the end result is the stitching is hidden deep down in the depths of the data layer, and i end up with a really clean Controller.

EDIT

This "stub technique" also works:

public void UpdateModel(Post post)
{
   var stub = new Review {PostId = post.PostId};
   CurrentEntitySet.Attach(stub);
   Context.ApplyCurrentValues(GetEntityName<Post>(), post);
}

But the problem is because Post is abstract, i cannot instantiate and therefore would have to check the type of Post and create stubs for every single derived type. Not really an option.

EDIT 2 (LAST TIME)

Okay, got the "stub technique" working with abstract classes, so now the concurrency issue is solved.

I added a generic type parameter to my UpdateModel method, and the special new() constraint.

Implementation:

public void UpdateModel<T>(T post) where T : Post, new()
{
   var stub = new T { PostId = post.PostId };
   CurrentEntitySet.Attach(stub);
   Context.ApplyCurrentValues(GetEntityName<Post>, post);
}

Interface:

void UpdateModel<T>(T post) where T : Post, new();

This prevents me from having to figure out the type of T manually, prevents concurrency issues and also prevents an extra trip to the DB.

Pretty groovy.

EDIT 3 (i thought the last time was the last time)

The above "stub technique" works, but if i retrieve the object beforehand, it throws an exception stating an entity with that key already exists in the OSM.

Can anyone advise how to handle this?

EDIT 4 (OK - this is it!)

I found the solution, thanks to this SO answer: Is is possible to check if an object is already attached to a data context in Entity Framework?

I had tried to "check if the entity is attached" using the following code:

ObjectStateEntry entry;
CurrentContext.ObjectStateManager.TryGetObjectStateEntry(entity, out entry);

But it always returned null, even through when i explored the OSM i could see my entity there with the same key.

But this code works:

CurrentContext.ObjectStateManager.TryGetObjectStateEntry(CurrentContext.CreateEntityKey(CurrentContext.GetEntityName<T>(), entity), out entry)

Maybe because i'm using Pure POCO's, the OSM had trouble figuring out the entity key, who knows.

Oh and one other thing i added - so that i don't have to add a specific repository for each entity, i created an attribute called "[EntityKey]" (public property attribute).

All POCO's must have 1 public property decorated with that attribute, or i throw an exception in my repository module.

So my generic repository then looks for this property in order to create/setup the stub.

Yes - it uses reflection, but it's clever reflection (attribute-based) and i'm already using reflection for plularization of entity set names from T.

Anyway, problem solved - all working fine now!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文