简体   繁体   English

使用实体框架6插入断开连接的相关实体

[英]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. 我从转置的XML文件中获取了一些数据,可以映射到我的实体。 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()? 我在阅读SO 实体框架是否可以通过单个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:' “如果您使用对新创建的对象而不是ID的对象引用,则无需每次都保存更改:”

My entities are derived from a dataset tables which all have a related Id columns. 我的实体是从均具有相关ID列的数据集表派生的。

And I guessing the answer is more or less that the related entity was created with something like this : item.SubItem = new SubItem(); 而且我猜答案是或多或少的是相关实体是用这样的东西创建的: item.SubItem = new SubItem(); rather than item.SubId = SubItem.Id; 而不是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}..?? 因此,对于dt ['Items']中的每一行,如果该行有一个子项new SubItem {除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. 因此,在解决问题之后,我发现是否创建了实体的新对象并将其映射到ID列以外的值,然后可以将该对象分配回父对象。

pseudo code is below: 伪代码如下:

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

myentityParent.ChildTableEntity.Add(myobject);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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