I have a problem with Entity Framework and ForeignKeys. I have a table "BC_Message_Assets" that has 3 FK (MessageId, AssetId and StatusId). I create my "MessageAsset" as follows
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 was against the FOREIGN KEY constraint "FK_BC_Message_Assets_BC_Assets". The conflict occurred in the database "Test", the table "dbo.BC_Assets", in the column "Identifier". Application completed.
When I look at the query, I notice that the parameter value for AssetId is “0”, despite the fact that I provided a “1” 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
, . "1" EntityKey, "0" ?