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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…