Reputation: 1313
I'm using Entity Framework with a set of 3 different tables, in a hierarchy. Think ApartmentUnit -> ApartmentComplex -> OwnerOrganization. Each has a primary key, and a foreign key to its owner, in the database. When I built the EF model, it created properties for each of those. Indeed, saving new instances of each is pretty easy. I also learned, for example, that to add a new unit, I first need to add an organization, add it to a new complex, then add that to the new unit before saving. A bit of work, but it makes sense.
Where I am confused now is, I have a new apartment unit, but it lives in an existing complex. I can build up a new complex object with the appropriate properties, and attach it to the new unit, but when I go to save the unit, the framework spits up a primary key violation in the apartmentComplex table, as it is trying to add the complex I attached as a NEW complex, not an existing one.
The workaround to me seems to be go and retrieve a new instance of the complex first, instead of building one - in effect, letting the EF build it instead of me - but that would mean another round-trip and seems like overkill to me. Is there a simpler way to save my new Apartment Unit?
Upvotes: 3
Views: 4904
Reputation: 2861
You can create the existing complex without going to the DB but you must attach it to the context before you save.
Complex existingComplex = new { ID = 1234 };
entitiesContext.AttachTo("Complexes", existingComplex);
newAppartment.Complex = existingComplex;
entitiesContext.SaveChanges();
Upvotes: 2