Can not insert new record to database in the related table

Last Reply on Dec 18, 2013 07:18 AM By RkHirpara

Posted on Dec 16, 2013 10:08 PM

       Just for test purposes I am trying to get the below code to work and using a foreign key constarint in my database, I have an Owners table related to a pets table "1 to many", and in the example below am trying to add the related table of pets but I get the error stated, I would appreciate some help please on what the issue is as I am new to databases, thanks

 

 

        OwnersPetsEntities context = new OwnersPetsEntities();

      

        Pet tmpPet = new Pet();

        Owner tmpOwner = new Owner();

 

        tmpOwner.Id = 1;

        tmpOwner.Name = "John";

        tmpOwner.Tel = "1234";

 

        tmpPet.Id = 1;

        tmpPet.OwnersId = 1;

        tmpPet.Name = tmpPetName;

        tmpPet.Type = tmpPetType;

        tmpPet.Colour = tmpPetColour;

 

        context.Owners.Add(tmpOwner);       "It goes past this part as ok"

        context.SaveChanges();

      

        context.Pets.Add(tmpPet);

        context.SaveChanges();      "Error:- Message=The INSERT    statement conflicted with the FOREIGN KEY constraint "Relationship". The conflict occurred in database"

  

 

Posted on Dec 18, 2013 07:18 AM Modified on on Dec 18, 2013 07:20 AM

Hi Snooker,

We can definitely help you, Rest assure,

First you have to check what PF-FK relation you have established... ?

Something is happening like you are inserting data to FK column and in PK Column there is not such data record, please make it sure,

also check it in SP that Entry in PK table should made first than only you have to enter data to the FK table

Thanks and Regards,

Rk_Hirpara

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html