getting error with context.SaveChanges() in EF code First

rehan

New Member
Error::\[code\]The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.\[/code\]
Code` \[code\] package_master p = new package_master(); public void addclientPackage(company company,string a) { string data = http://stackoverflow.com/questions/8585465/a.Replace(",", ""); data.Trim(); foreach (char d in data) { int pID = int.Parse(d.ToString()); var packageData = http://stackoverflow.com/questions/8585465/db.package_master.Find(pID); p.cost = packageData.cost; p.package_name = packageData.package_name; p.client_id = company.company_id; var max = (from package in db.package_master select package.MCheck_id).Max(); p.MCheck_id = max + 1; db.package_master.Add(p); this.db.SaveChanges(); //db.SaveChanges(); int packageID = p.package_id; //add checks int mchechID = packageData.MCheck_id; List<check_master> row = (from table in db.check_master where table.MCheck_id == mchechID select table).ToList(); foreach (var ro in row) { ro.MCheck_id = p.MCheck_id; ro.package_id = packageID; db.check_master.Add(ro); db.SaveChanges(); } } }`\[/code\]
Code Explanation:: I have two table Package_master and check_master(one to many relationship). Here in this code i tried to insert multiple packages(existing) i.e package table and check_master hold some initial row data and i tried to re-insert existing row with new id by passing existing id(string a) string where each string char holds existing package id(use first foreach loop for insert package in package master).
Now further i searched for existing checks in check_master for that packageid(existing) and finally fetched the row data for matching checks(if found) and inserting them again in check_master with new check_id(use second foreach loop for this) for each package master.

error Situation
Getting this error while passing 2 or more char for \[code\]string a\[/code\] parameter where one of the char hold few checks in database(as you see it in my code i used foreach loop for every string char i am passing to insert new rows in check_master table).

Situation in which this code wrrking fine
When i pass a \[code\]string a\[/code\] with n char in which no char holds checks in check_master table.

Updated
when i remove relationship b/w package_master and check_master from database and updated my model accordingly then this issue is resolved
That means when i inserted few new rows in check_master then at that time i need to show relationship of those row with package_master
I am confused , can someone please explain me the best way to utilize one to many with insert/delete/update in EF code first with example
 
Top