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

c# ef-migrations entity-framework entity-framework-core

Question

Consider entities Company and Product:

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.

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. If it fails, we can go back to the original source of data and see what is wrong with this specific Company

1
3
3/12/2020 6:09:33 AM

Popular Answer

Delete the created ForeignKey codes which are created by EF. 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);
1
3/12/2020 5:18:56 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow