Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE conflicts with the REFERENCE constraint while using nullable foreign key

I'm using ASP.Net MVC. I have two classes which are one-to-many and many-to-many related.

public class Image
{
    public Image() { }

    public long Id { get; set; }

    // other properties are removed for clarity

    public virtual IList<Branch> Branches { get; set; }
}


public class Branch
{
    public Branch() { }

    public long Id { get; set; }

    // other properties are removed for clarity

    public long? ImageId { get; set; }
    public virtual Image Image { get; set; }

    public virtual IList<Image> Images { get; set; }
}

Branches can have multiple images (Branch.Images). But I wanted to store their main image separately (Branch.Image). I think this may help with the speed. Since branches may have no image, this property is defined nullable. As references state, this kind of definition should define a foreign key in Branches table, and it does. But the problem is when an image which is a branch's main image is being deleted. It causes this error:

The DELETE statement conflicted with the REFERENCE constraint "FK_Branches_Images_ImageId". The conflict occurred in database "Database", table "Branches", column 'ImageId'. The statement has been terminated.

But it was supposed to set the foreign key to null as there is no main image for that branch.

Should I use Fluent API too or there is some problem in model definition?

like image 849
mrmowji Avatar asked Sep 13 '25 10:09

mrmowji


1 Answers

The automatic set to null only works if the children are loaded into the context as well, not only the parent entity. You need to Include the children into your parent before deleting it.

like image 126
Math M. Avatar answered Sep 15 '25 01:09

Math M.