相关实体的更新 [英] Update Of Related Entities

查看:63
本文介绍了相关实体的更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道支持以下情况的最佳方式是什么:

I'm wondering what is a best way to support following scenario:

 

1。实体产品具有ProductAttributes(1> n关系)

1. Entity Product has ProductAttributes (1->n relation)

2。当产品更新时,所有相关属性应该被新的"对象"替换。 (动态更新的逻辑过于复杂,因此"替换"所有项目要容易得多)

2. When a product updated, all the related attributes should be replaced with new "objects" (the logic for dynamic update is too complex, so it's much easier to "replace" all the items)

3。产品正在客户端更新(连同相关属性),并发送到服务(WCF)

3. Product is being updated on the client-side (together with related attributes), and sent to the service (WCF)

 

我试过使用"ApplyCurrentValues",但是此方法可以在标量值上运行,并且不会更改相关实体。

I tried using "ApplyCurrentValues", however this method operates over scalar values and doesn't change related entities.

EF4如何支持这种情况?

How would EF4 support such a scenario?

 

问候,

标记

推荐答案

您好,

您必须附加从WCF请求收到的产品。这也将附加所有ProductAttributes。然后,您必须通过调用context.ObjectStateManager.ChangeObjectState(entity,EntityState.Modified)将Product及其所有属性设置为Modified状态。
这将允许您更新产品及其所有属性。如果您还需要删除或插入相关属性,您必须知道哪一个。例如,对于标记为删除的属性使用否定Id,对于标记为
插入的属性,Id等于零。

you have to Attach Product received from WCF request. This will also attach all ProductAttributes. Then you have to set Product and all its attributes to Modified state by callcing context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified). This will allow you to update Product and all its attributes. If you also need to delete or insert related attributes you have to know which one. For example use negative Id for attributes marked for deletion and Id equal to zero for attributes marked for insertion.

因此更新方法可能如下所示:

So the update method can look like:

public void Update(Product product)
{
 context.Attach(product);
 context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);

 foreach (var attribute in product.Attributes)
 {
  EntityState state = EntityState.Modified;

  if (attribute.Id == 0)
  {
   state = EntityState.Added;
  }
  
  if (attribute.Id < 0)
  {
   attribute.Id *= -1;
   state = EntityState.Deleted;
   // If you are lucky, you will not need to mark relation for deletion as well
// context.ObjectStateManager.ChangeRelationshipState(attribute, product, a => a.Product, EntityState.Deleted); }
context.ObjectStateManager.ChangeObjectState(attribute, state); }




context.SaveChanges(); }

最好的问候,

Ladislav

Best regards,
Ladislav


这篇关于相关实体的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆