实体框架,外键和EntityKeys实体、框架、EntityKeys

2023-09-05 02:36:58 作者:筱筱

我有实体框架和ForeignKeys的一个问题。 我有一个表BC_Message_Assets其中有3 FK的(的MessageId,由assetid和StatusId)。 我创建MessageAsset像这样

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 :

INSERT语句冲突与外键约束FK_BC_Message_Assets_BC_Assets。发生在数据库中的测试,表dbo.BC_Assets,列'身份证'的冲突。   该语句已终止。

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.

当我看着查询,我注意到,对于由assetid参数值为0尽管我到的EntityKey提供的1。下面是生成的查询:

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

我无法解释发生了什么。我为1的硬codeD上的EntityKey,我在查询中获得0?

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.

但我发现这个问题的原因。问题是,在我的BC_Message_Assets表的PK是基于2 FK(的MessageId和由assetid)。用一个简单的标识符(INT +身份证),它的工作原理没有问题......奇怪!

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 !