【发布时间】:2015-07-29 18:15:14
【问题描述】:
我有从我的 DTOCollection 进行批量插入的方法,它有 3 级循环。
public List<FirstCollectionDTO> BulkInsert(List<FirstCollectionDTO> collection)
{
using (var db = new DemoEntities())
{
//Setting Auto Detech Changes false when starting loop
db.Configuration.AutoDetectChangesEnabled = false;
//Looping start
collection.ForEach(myitem =>
{
myitem.SecondCollection.ForEach(secondLevel =>
{
//Some Operation Over here
secondLevel.ThirdCollection.ForEach(thirdItem =>
{
var myEntity= new MyTable()
{
Level=thirdItem.Name,
Method=thirdItem.Method,
Representation=thirdItem.Representation,
};
var insertedItem = db.MyTable.Add(myEntity);
//Setting the reference of id to the
//DTO after the save changes.
//This seems always 0 as it this time
// it have no id only after save changes the id be passed into InsertedItem , I have to pass the reference to myDTO also
thirdItem.Id = insertedItem.Id;
});
});
});
//Setting Auto Detech Changes true when starting loop
db.Configuration.AutoDetectChangesEnabled = true;
// Here I save my changes
db.SaveChanges();
return collection;
}
}
如果 INSERT 操作成功,服务器生成的值将被写回。那么我如何将这个值也放入我的 DTO 中。
保存更改后如何获取插入对象的 Id,我需要维护 3 级集合的关系,即使
【问题讨论】:
-
值在
SaveChanges期间被分配并读回实体,因此在此之前您无法知道它们。 -
@GertArnold 有什么办法可以在保存更改后获取 id 并保持 3 个级别的关系。
-
thirdItem可以有一个属性MyTable,包含实体对象,所以thirdItem.Id可以返回实体的ID。 -
@GertArnold,
ThirdItem是 DTO 对象,我希望避免从 DTO 引用 EF -
然后在此过程中使用接口(用于 EF 类)或构建 DTO/Entity 对的字典。
标签: c# entity-framework orm pass-by-value