4

I'm using code-first with EF Core 3.1.2

I have established the following two-way one-to-one relationship in the OnModelCreating method of my DbContext.

modelBuilder.Entity<Inspection>()
    .HasOne<Defect>(i => i.SpecialDefect)
    .WithOne(d => d.SpecialInspection);

This creates foreign key constraints in the database. I would like these constrains to be non-enforced. i.e. I would like the "Enforce Foreign Key Constraint" option to be set to "No". By default, this is set to yes.

enter image description here

Is this possible? If so, how might I do this?

3
  • Why do you want this? Is it for performance reasons? Or did the FKs prevent you from adding an Inspection without a SpecialDefect? The answer to the second problem is not to disable the FKs. In SQL, the way to implement the Inspection<->SpecialDefect relation would be to add a single InspectionId property to SpecialDefect. Commented Jul 16, 2020 at 11:06
  • Did you find a solution for this? In my case I have a Foreign Key value that I don't want to loose when the parent record is deleted. Also I would like to be able to navigate over the NOT PK to the parent table. Commented Apr 16, 2021 at 14:26
  • In my case, I ended up working around this by changing the way the relationship was implemented in my model. It would be interesting to know how to configure EF Core to set some of these specialised options, though. Commented Jun 8, 2021 at 4:07

1 Answer 1

-1

If you need to add a row with a NULL value in column "DefectId", you can easily define that as a NULLABLE in the corresponding class.

public int? DefectId {get;set;}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.