views:

400

answers:

2

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 ?

A: 

As you say you programmed 1,1,1 but got 47,0,1

It was 2 of the values that were not expected.

One thing that could be happening is that there is some other code that is generating this row. When you save it saves the row with the error first, this throws and exception, and you never see the row that you created.

Try writing a unit test with only the code in your question.

Shiraz Bhaiji
A: 

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 !

Greg