I've got a problem with the Entity Framework and the ForeignKeys. I've got a table "BC_Message_Assets" which has 3 FK's (MessageId, AssetId and StatusId). I create my "MessageAsset" like this
MessageAsset messageAsset = new MessageAsset();
messageAsset.MessageStatusReference.EntityKey = new EntityKey("MyEntities.MessageStatusSet", "Id", 1);
messageAsset.AssetReference.EntityKey = new EntityKey("MyEntities.AssetSet", "Id", 1);
messageAsset.MessageReference.EntityKey = new EntityKey("MyEntities.MessageSet", "Id", messageId);
context.AddToMessageAssetSet(messageAsset);
context.SaveChanges();
But I got the following exception :
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_BC_Message_Assets_BC_Assets". The conflict occurred in database "Test", table "dbo.BC_Assets", column 'Id'. The statement has been terminated.
When I look at the query, I notice that the parameter value for AssetId is "0" despite that I provided "1" to the EntityKey. Here's the generated query :
exec sp_executesql N'insert dbo.[BC_Message_Assets]([MessageId], [AssetId], [CompletionTime], [StatusId]) values (@0, @1, null, @2) ',N'@0 int,@1 int,@2 int',@0=47,@1=0,@2=1
I can't explain what happens. I hardcoded "1" in the EntityKey and I received "0" in the query ?
I got the problem with my unit tests.
But I found cause of the problem. The problem was that the PK on my BC_Message_Assets table was based on the 2 FK (MessageId and AssetId). With a simple identifier (int + identity), it works without problem ... Strange !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With