[英]c# System.Data.Entity.Infrastructure.DbUpdateException inserting a new record
I've created an import system in my application. 我在应用程序中创建了一个导入系统。
I start from an upload of a JSON, this JSON is received as string from my web service, then transformed in an object called tpp
(I've checked and my object is correctly created and populated). 我从上传JSON开始,从我的Web服务以字符串形式接收此JSON,然后将其转换为名为tpp
的对象(已检查并正确创建并填充了我的对象)。
Then I do some inserts in my database: 然后在数据库中插入一些内容:
db.States.Add(tpp);
db.SaveChanges();
It works fine. 工作正常。 Then, tpp
contains cities
, so I use this code: 然后, tpp
包含cities
,因此我使用以下代码:
foreach (City curCity in tpp.Cities)
{
db.Cities.Add(curCity);
db.SaveChanges();
}
In this db.SaveChanges()
I receive a System.Data.Entity.Infrastructure.DbUpdateException
regarding saving foreign keys. 在此db.SaveChanges()
我收到有关保存外键的System.Data.Entity.Infrastructure.DbUpdateException
。
tpp.Cities contains a list of Streets ( List<Street> Streets
in my City class), but I save them later in another table and also States contains a list of Cities but it doesn't throw an exception. tpp.Cities包含街道List<Street> Streets
(在我的City类中为List<Street> Streets
),但是稍后我将它们保存在另一个表中,States也包含城市列表,但它不会引发异常。
So, why my code is returning an exception when I add a city in foreach loop? 那么,为什么在foreach循环中添加城市时我的代码为何返回异常?
If your data structure on the POCOs and incoming JSON is right than you shouldn't have to add the child items manually. 如果您在POCO和传入JSON上的数据结构正确,则不必手动添加子项。 From your code it appears it is. 从您的代码看来它是。 So just adding the ttp should take care of everything as long as ttp.Cities.Streets ... and so on are populated. 因此,只要填充ttp.Cities.Streets ...等,只需添加ttp就可以处理所有事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.