3

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?

Mike K
  • 1,313
  • 2
  • 18
  • 28
  • I vaguely remember that EF builds both the link to the parent object as well as the ID field itself. So you should have both "Complex" and "ComplexID" in your ApartmentUnit object. Just add a new ApartmentUnit object and set it ComplexID field (not touching the Complex link) and saving it could work. – Stephen Chung Mar 30 '11 at 07:22

1 Answers1

2

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();
Fabian Nicollier
  • 2,811
  • 1
  • 23
  • 19
  • Would I need to build up the whole object, or could I just put in the primary key, as you have done? – Mike K Mar 30 '11 at 06:44
  • As in my example, you just need to provide the primary keys which are necessary to attach to the context. – Fabian Nicollier Mar 30 '11 at 07:01
  • 1
    This was close, but I got an exception indicating the EntityKey was null. I changed it from context.Attach(existingComplex) to context.AttachTo("Complexes", existingComplex), per http://stackoverflow.com/questions/700192/how-do-can-i-attach-a-entity-framework-object-that-isnt-from-the-database. Then it worked. – Mike K Mar 31 '11 at 09:13
  • You are correct, my mistake. I'll edit my post to reflect this. – Fabian Nicollier Mar 31 '11 at 12:25