[英]c# entity framework loop through records savechanges() error
I am doing an C# Entity Framework
Application. 我正在做一个
C# Entity Framework
应用程序。
I am migrating data from a couple of tables from one database to another database. 我正在将数据从几个表从一个数据库迁移到另一个数据库。 Those tables are called with the same name.
这些表以相同的名称调用。
Here is my code 这是我的代码
string ConnexionOrigen = ReadConnectionBiz.GetOrigen(); string ConnexionDestino = ReadConnectionBiz.GetDestino(); using (var db = new MigrateModel(ConnexionOrigen)) { db.Configuration.LazyLoadingEnabled = false; db.Configuration.ProxyCreationEnabled = false; db.Configuration.AutoDetectChangesEnabled = false; List<Promocion> promo = await (from p in db.Promocions .Include(a =>a.PromocionAddresIds) where (p.CAM_ID == 107936 || p.CAM_ID == 107937) select p) .AsNoTracking() .ToListAsync(); var dbDestino = new MigrateModel(ConnexionDestino); foreach (Promocion pp in promo) { try { dbDestino.Promocions.Add(pp); await dbDestino.SaveChangesAsync(); } catch (Exception ex) { string err = ex.InnerException.InnerException.Message.ToString(); } }
I search in Origen
Database from table Promocions
and insert those records in Promotions table in Destino Database . 我从
Promocions
表中搜索Origen
数据库,并将这些记录插入Destino数据库中的Promotions表中。
I include a child table called PromocionAddresIds
that is migrated too. 我包括一个也称为
PromocionAddresIds
的子表。
Everythig works fine... Everythig运作良好...
The table PromocionAddresIds
has a constraint with a table that it is not been migrated. 表
PromocionAddresIds
具有未迁移表的约束。
When I insert the Promotions
with cam_id=107936
it thrown an exception of contraint violation
... Witch is correct... 当我插入带有
cam_id=107936
的Promotions
时,抛出了contraint violation
的异常...女巫是正确的...
But when it read the next Promotions
record with Cam_id =107937
. 但是当它读取下一个带有
Cam_id =107937
Promotions
记录时。 That record has no record in table PromocionAddresIds, so it must be inserted, but it thrown the same error exception... 该记录在表PromocionAddresIds中没有记录,因此必须将其插入,但会引发相同的错误异常...
It appears that await dbDestino.SaveChangesAsync();
似乎正在
await dbDestino.SaveChangesAsync();
still have the all record or it persist somewhere... 仍然拥有所有记录,或者它持续存在某处...
I have tried adding 我尝试添加
dbDestino.Promocions.Remove(pp);
inside the catch exception
, but it did not work. 里面的
catch exception
,但是没有用。
I do not have any clue how to solve it. 我不知道如何解决。
Any ideas? 有任何想法吗?
Thanks 谢谢
You created a single instance of data context for all iterations of the loop. 您为循环的所有迭代创建了一个数据上下文实例。 All objects added to the context will live there until the context is disposed or cleared.
所有添加到上下文中的对象都将驻留在那里,直到上下文被处置或清除为止。 The situation you observe is:
您观察到的情况是:
Please also note that calling "save changes" after each entity usually is not efficient. 另请注意,在每个实体之后调用“保存更改”通常效率不高。 It is better to insert a portion of entities (let's say 100) and persist it in one shot.
最好插入一部分实体(例如100),然后将其保留一枪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.