简体   繁体   中英

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).

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:

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.

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.

So, why my code is returning an exception when I add a city in foreach loop?

If your data structure on the POCOs and incoming JSON is right than you shouldn't have to add the child items manually. 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.

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