Skip to content

Exception On Foreign Constraint

Kacey Ezerioha

Asked Oct 15, 2012, 4:54 AM EDT1 answer
Share
LinkedInX
Hi, 

I have a table StaffLevelMapping that has a foreign key column, which is a primary key another table AcademicLevel. It raises an exception that the Insert statement conflicted with a foreign key and it has its reference on the foreign key and the table in which it's a primary key. I know this usually happens if the value you are inserting does not exist in it's original table. But this does exist actually. I tried inserting it directly in sql server and it worked perfectly. But through my code it doesn't work. What surprises me the most is I used the same insert logic for the rest of my tables and I don't have problems save this one with this very table. Please I need a very quick help on this I have not slept in 2 days because of this error.

Here's my insert code below:


C#
	public static StaffLevelMapping AddStafflevel(int staffId, int levelId, bool isEnabled)
        {
            var context = ObjectContextHelper.CurrentObjectContext;
            var staffLevel = context.StaffLevelMappings.CreateObject();


            staffLevel.StaffID = staffId;
            staffLevel.ID = levelId;
            staffLevel.IsEnabled = isEnabled;
            context.StaffLevelMappings.AddObject(staffLevel);
            context.SaveChanges();


            return staffLevel;
        }

Many thanks in advance to that special person that can put me out of this misery.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Sandeep Singh Shekhawat
    0
    Rebuild entity framework and check constraint among tables as well in database tables 

    OR

    Verify Model ==== Right Click an Open Area in the Modal and 'verify' and Save if verify successful or not then check constariant on model as same in sql server tables.

    Thanks
    Sandeep
    0