Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 328
Alireza Avatar asked Nov 02 '25 03:11

Alireza


1 Answers

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);