EF, updating inserted child object's auto incremented id

EF, updating inserted child object's auto incremented id

Old forum URL: forums.lhotka.net/forums/t/9317.aspx

chrisdot posted on Tuesday, August 03, 2010


I'm using EF4 to access my DB. I have a little hierarchy with a root BO (let's call it RootBO), a child list BO (deriving from BusinessListBase, let's call it ChildListBO), and finally children (deriving from BusinessBase, let's call them ChildBO).It looks simple.

Here is my question: when in a UI, I edit a RootBO object with all the descending objects (down to ChildBO), and that a ChildBO instance has newly be created, how can I update easily it's id ? I mean, when you reach the Child_Insert(..) method, and that you get a context from the parent objects, it is not possible to get back the auto generated id (by the DB) at that moment.

Is there another trick than just reloading the full hierarchy after RootBO's DataPortal_Update() ? How can we proceed?


My code looks like:

private void Child_Insert(EntitiesContext o_context, DBEntity1 parentEntity)

Entity2 o_new = new Entity2();
o_new.Label = Label;


//at this point I do not have any id of the new created entity,

//so my BO's data is not complete



(I'm just wondering more and more why I still should continue to use EF to access my DB. I think that the good old SQL code could handle it as nice as EF)


Thanks a lot,


ajj3085 replied on Wednesday, August 04, 2010

I'm not sure if this will work in EF but in Linq to Sql I would hook up a PropertyChanged event handler and when the Id property changes and record it. 

xAvailx replied on Thursday, August 05, 2010

If you are passing the context around, you don't need to worry about setting the id's, EF will do it for you (you have to attach all the entities first before saving however as I understand it).

If you are not passing in the context, then traditionally, you would pass the parent as a reference, which at that point is saved and has the id you need. 

Copyright (c) Marimer LLC