Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Wierd insert error on Foreign key conflict

$
0
0

Dear all

I have a weird issue while entering a data into one table which reference as a FK in an other

If I enter manually the following in my PropertyType Table :

INSERT INTO [RealEstateAgent].[dbo].[PropertyType]
           ([PropertyId]
           ,[TypeName]
           ,[PropertyTypeId])
     VALUES
           (123,'test',0)
GO

Then I get the following error :

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_PropertyType_Vebra_PropertyDetails". The conflict occurred in database "RealEstateAgent", table "dbo.Vebra_PropertyDetails", column 'Id'.

Which is correct because the PropertyId value I am inserting is not existing in the PropertyDetails. So if I enter instead the following querry :

INSERT INTO [RealEstateAgent].[dbo].[PropertyType]
           ([PropertyId]
           ,[TypeName]
           ,[PropertyTypeId])
     VALUES
           (24072341,'test',0)
GO

Then all works fine and data gets inserted correctly. So far so good.

The problem is occurring when I am inserting the records above using Entity Framework as follow :

RealEstate_Model.PropertyType A = new RealEstate_Model.PropertyType();
                    A.PropertyId = Tp.PropertyId;
                    A.TypeName = Tp.Name;
                    A.PropertyTypeId = (int)(from t in context.GetPropertyType(int.Parse(Tp.SearchCriteria)) select t).FirstOrDefault();
                    context.PropertyTypes.AddObject(A);
                    context.SaveChanges();

All field valule are the same as in the succesfull query I was executing manually but when the context.SaveChanges() is executed, I get and exception with same error I get with the first querry I was executing manually.

Did I miss something here ?

regards


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>