I've been running into a problem where using objects from two datacontexts that are of same type, won't submit objects on. To make this matter simple consider the following LINQ-to-SQL design where we have database tables describing cars and persons.
+--------------+ +--------+
| Car | 1 1 | Person |
+--------------+---------+--------+
| Registration | | name |
| ownerId {FK} | +--------+
+--------------+
Then we've got two data repositories that have an instance to the same datacontext class having the following methods:
public OwnerRepository {
private MyDataContext db;
public Person GetOwnerByName(string ownerName)
{
return (from person in db.Persons
where person.Name == ownerName
select person).SingleOrDefault();
}
}
public CarRepository {
private MyDataContext db;
public Car GetCarByRegistration(string registration)
{
return (from car in db.Cars
where car.Registration == registration
select car).SingleOrDefault();
}
public void RegisterOwner(Person owner, string registration)
{
var car = GetCarByRegistration(registration);
car.Owner = owner;
db.SubmitChanges();
}
}
Say we get a Person from the OwnerRepository and use it to register that person as a owner to a car:
var owner = ownerRepository.GetOwnerByName("Peter Pan");
carRepository.RegisterOwner(owner, "TOO COOL");
The method RegisterOwner
will throw an exception because the Person object won't be recognized by the datacontext (even though it is of the same type). What can you do to go around this problem?