2

I have an entity that has an int as its primary key that is set to storegeneratedpattern = none so that we provide the id client side.

This entity has child entities that reference back to it via an association with navigation and foreign key id.

If I create a new parent entity and add a child, then set the parent entities primary key and save, the fix up of the foreign key for the child happens AFTER the save and is not persisted to the database.

eg

    engine = new Engine();
    part = new Part();
    engine.Parts.Add(part);
    engine.Id = 6;
    engineRepository.Save(engine);

The save is simply

Context.Engines.AddObject(entity);
Context.SaveChanges();

After the save "part" will have a foreign key "EngineId" = 6, but in the database it will be "EngineId" = 0, ie it appears that the fixup happened after the save.

What am I missing here? It all works fine if the storegeneratedpattern for engine is identity.

Crab Bucket
  • 6,219
  • 8
  • 38
  • 73
Darren Hall
  • 97
  • 1
  • 1
  • 9

2 Answers2

0

I think if you are creating your own Id for the engine, you have to create it for the part as well.

engine = new Engine();
part = new Part();

part.engineid = 6

engine.Parts.Add(part);
engine.Id = 6;
engineRepository.Save(engine);
Greg
  • 2,654
  • 3
  • 36
  • 59
  • That is one possibility but it means that the whole auto fix up benefit of EF is negated. In actuality we have a huge graph and would have to walk the entire thing to set all the appropriate ids. I have provided the answer we eventually used below. – Darren Hall Jul 18 '13 at 12:43
0

The resolution in this case appears to be that you save the graph twice, once to create the fix up and once to save the fix up. It's not a great solution and I still don't understand why we are having to do it but at least it means that we can let EF take care of id resolution.

Crab Bucket
  • 6,219
  • 8
  • 38
  • 73
Darren Hall
  • 97
  • 1
  • 1
  • 9