简体   繁体   中英

Inserting Disconnected Related Entities with Entity Framework 6

I have some data from an XML file that I have transposed and I can map to my Entities. So now I want to save them all to the database .

I was reading on SO Can Entity Framework add many related entities with single SaveChanges()?

The accepted answer does not have too much info but this statement:

'You don`t need to save changes every time if you use objects references to newly created objects not IDs:'

My entities are derived from a dataset tables which all have a related Id columns.

And I guessing the answer is more or less that the related entity was created with something like this : item.SubItem = new SubItem(); rather than item.SubId = SubItem.Id;

So should I traverse my data tables and translate my dataset tables into Entities by creating the objects from the tables and adding them to the context.

So for each row in dt['Items'] if row has a subitem new SubItem {all values except the Id}..??

Any example code would be appreciated.

So after working to resolve the issue I discovered if I create a new object of my entity and map values to it excluding the ID column I can then assign this object back to the parent.

pseudo code is below:

myobject = new myobject(){ param1 = oldobject.param1}

myentityParent.ChildTableEntity.Add(myobject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM