简体   繁体   English

将 EF 核心设置为不为特定导航属性创建数据库外键

[英]Setup EF core to not create Database Foreign Key for specific Navigation Property

Consider entities Company and Product :考虑实体CompanyProduct

public class Company
{
    prop Guid Id {get; set;}
}

public class Product
{
    prop Guid CompanyId {get; set;}
    prop Company Company {get; set;}
}

When creating migrations, I want the relationship from Product to Company not to create a foreign key constraint in the database.创建迁移时,我希望从ProductCompany的关系不要在数据库中创建外键约束。

I understand all the problems with not creating foreign keys, I always create foreign keys, but in one specific problem, I want to avoid one foreign key.我了解不创建外键的所有问题,我总是创建外键,但在一个特定问题中,我想避免使用外键。 How to do that?怎么做?

Explanation: This is some diagnostics data, so I need to keep all the info that can help diagnostics, even when the main entity cannot be inserted.说明:这是一些诊断数据,所以我需要保留所有有助于诊断的信息,即使无法插入主实体。 If that is inserted, we'll be happy to use Navigation properties to navigate to it.如果插入,我们很乐意使用 Navigation 属性导航到它。 If it fails, we can go back to the original source of data and see what is wrong with this specific Company如果失败,我们可以回到原始数据源,看看这个特定Company有什么问题

Delete the created ForeignKey codes which are created by EF.删除EF创建的已创建的ForeignKey代码。 And then do the migration action.然后执行迁移操作。 Hope this will help you.希望这会帮助你。 Eg: (some lines like below)例如:(一些像下面这样的行)

                table.ForeignKey(
                    name: "FK_Products_Companies_CompanyId",
                    column: x => x.CompanyId,
                    principalTable: "Companies",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);

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

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