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'.\r\nThe 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 ?