Glauco Cucchiar
Glauco Cucchiar

Reputation: 774

EF6 - Insert multiple entities and update last

I'm working with EF6 and I need to insert 2 entities and after update the last with some data of first. This is an example:

var entity1 = new EntityT1();
setData(entity1);

var entity2 = new EntityT2();
setData(entity2);

ctx.Set<EntityT1>.Add(entity1);
ctx.Set<EntityT2>.Add(entity2);
ctx.SaveChanges();

//this is the result I would like
entity2.Prop1 = entity1.IdFromDb;

Can I make this in one step? or... I need to make two SaveChanges? thanks

Upvotes: 0

Views: 42

Answers (1)

Jonathan Magnan
Jonathan Magnan

Reputation: 11347

Can I make this in one step? or... I need to make two SaveChanges? thanks

You will need to do it in two SaveChanges. There is nothing that ensures you that entity 1 will be saved before entity 2 (unless they have some dependency) since the order you add your entity in the ChangeTracker doesn't matter.

If there is a relation between EntityT1 and EntityT2, I suggest you to use navigation property if that's the key but I don't think this is the scenario you are looking for.

Upvotes: 1

Related Questions