Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

c# - Move child entities to a new parent entity

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
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
   }
}

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).

EDIT: 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;
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...