将子实体移到新的父实体 [英] Move child entities to a new parent entity

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

问题描述

将子实体从一个父实体移动到另一个父实体的最佳方法是什么?

What is the best way to move child entities from one parent entity to another? Is there a method inside the ObjectContext or DbContext that allows us to accomplish this?

public class Person
{
   public int PersonId
   public ICollection<Car> Cars
}

public class Car
{
   public int CarId
   public string Color
}

编辑:我当前正在首先将EF 4.0模型与POCO模板一起使用。

I'm currently using EF 4.0 model first with POCO template.

推荐答案

在这个示例中,我想说的是要更改车主。如果没有严重的不利因素反对在 Car 的汽车中添加对 Person 的反向引用,则可以使用以下方法:

I'd say what you want to accomplish is changing the owner of the car in this example. If there are no serious cons against adding a back reference to Person in the Car i'd go with something like:

public class Car
{
   ...
   public virtual Person Owner { get; protected set; }

   public void ChangeOwner(Person newOwner)
   {
          // perform validation and then 
          Owner = newOwner;
          // maybe perform some further domain-specific logic
   }
}

注意:受保护的设置方法是强制由外部使用者调用 ChangeOwner 方法。 EF可以通过自动生成的POCO类代理来正确设置它(假设您使用它们)。

NOTE: the protected setter is to enforce calling the ChangeOwner method by external consumers. EF wil be able to set it properly thanks to the autogenerated proxies for POCO classes (assume you use them).

编辑:
如果没有可能要添加对 Person 的反向引用,从域逻辑的角度来看,您仍然具有相同的目标。您只想更改车主。这样的操作涉及两个实体,因此我可能会使用一种放置在实体外部某处的方法(无论应将其放置在设计良好的系统中的什么位置):

In case there is no possibility to add a back reference to Person, you still have have the same goal looking from the domain logic perspective. You just want to change owner of a car. Such operation involves two entites so i'd probably go with a method placed somewhere outside the entity (regardless of where it should be placed in a well designed system):

public void ChangeCarOwner(Person originalOwner, Person newOwner, int carId)
{
    Car car = originalOwner.RemoveCarOwnership(carId);
    newOwner.AddCarOwnership(car);
}

public class Person
{
    ...
    public Car RemoveCarOwnership(int carId)
    {
        Car car = this.Cars.Single(c => c.Id == carId);
        this.Cars.Remove(car);
        return car;
    }
}

这只是概念性的一段代码,当然可以写得更好(确保旧主人确实拥有这辆车等),但是我只是想提出一个我将如何处理的想法。我还省略了 AddCarOwnership 的实现,因为我认为它相当麻烦。我介绍了那些方法,这些方法会导致添加和删除所有权可能会触发特定人员内部的其他逻辑。

This is just a conceptual piece of code and it most certainly can be written better (making sure the old owner actually owns the car etc.), but i just wanted to present an idea of how would i approach it. I also ommited the implementation of AddCarOwnership cause i suppose it's pretty strainghtforward. I introduced those methods cause adding and removing ownership may trigger some further logic "inside" a particular person.

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

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