简体   繁体   English

地图关系实体框架出错

[英]Error with map relationship Entity Framework

I'm having trouble creating a solution to this business rule. 我在为该业务规则创建解决方案时遇到了麻烦。

I currently have 1 client, 1 correspondent and 1 store. 我目前有1个客户,1个通讯员和1个商店。 Both use the same address table. 两者都使用相同的地址表。 As the client, correspondent, and store tables can not have the auto-generated Id, I have decided to use GUIDs to avoid duplicate errors in the Address table. 由于客户端,通讯录和商店表不能具有自动生成的ID,因此我决定使用GUID来避免地址表中的重复错误。 In this case the address table should look like this: 在这种情况下,地址表应如下所示:

AddressId  - ReferenceId          - Street
1          - GuidOfCorrespondent  - St. one
2          - GuidOfStore          - St. two
3          - GuidOfCustomer       - St. three

But I'm having trouble mapping entities. 但是我在映射实体时遇到麻烦。 Here's the template I'm trying to do: 这是我想要做的模板:

AddressMap() 
{
    HasKey(x => x.AddressId);

    Property(x => x.Street)
        .IsRequired()
        .HasMaxLength(60);

    Property(x => x.Number)
        .IsRequired();

    HasRequired(x => x.Correspondent)
        .WithMany(x => x.Adresses)
        .HasForeignKey(x => x.ReferenceId);

    HasRequired(x => x.Customer)
        .WithMany(x => x.Adresses)
        .HasForeignKey(x => x.ReferenceId);

    HasRequired(x => x.Store)
        .WithMany(x => x.Adresses)
        .HasForeignKey(x => x.ReferenceId);
    }

I'm getting this error: 我收到此错误:

The INSERT statement conflicted with the FOREIGN KEY constraint \\"FK_dbo.Address_dbo.Customer_ReferenceId\\". INSERT语句与FOREIGN KEY约束\\“ FK_dbo.Address_dbo.Customer_ReferenceId \\”冲突。 The conflict occurred in database \\"Correspondent\\", table \\"dbo.Customer\\", column 'StoreId' 数据库\\“ Correspondent \\”,表\\“ dbo.Customer \\”的列“ StoreId”中发生了冲突

Can someone help? 有人可以帮忙吗?

尝试在插入地址之前插入所有子实体

If the Correspondent has a navigation property of Address then you can populate the Address at the same time as you populate the Correspondent. 如果通讯员的导航属性为“地址”,则可以在填充通讯员的同时填充“地址”。 Just leave the AddressId on the Correspondent and the AddressId on the Address as zero. 只需在通讯录上保留AddressId,在地址上保留AddressId为零。

Then when you as enity framework to insert the Correspondent, it will insert the Address record first, then populate the AddressId on the Correspondent before then inserting the Correspondent record. 然后,当您作为实体框架插入通讯录时,它将首先插入地址记录,然后在通讯录上填充AddressId,然后再插入通讯录。

在这种情况下,您可能同时插入了客户和地址,您只需插入地址,保存更改然后插入客户,还可以使sql对外键约束不敏感,并且如果要插入实体,则使外键列为nullabe在子实体之前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM