Entity Framework 4 entity with storegeneratedpattern = none doesn't update foreign keys when saved

StackOverflow https://stackoverflow.com/questions/17332545

  •  01-06-2022
  •  | 
  •  

Domanda

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.

È stato utile?

Soluzione 2

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.

Altri suggerimenti

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top