0

I'm deleting a parent entity in my MVC controller and getting this error:

[SqlException]: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.MessageThread_dbo.Listings_ListingID". The conflict occurred in database "MyDB", table "dbo.MessageThread", column 'ListingID'. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

MessageThread table is mapped in EF like this:

// Relationships
this.HasOptional(t => t.Listing)
        .WithMany(t => t.MessageThreads)
        .HasForeignKey(d => d.ListingID);

The ListingID (parent) column in MessageThread (child) is nullable

I've looked at this post but the answers didn't make it work.

According to this, shouldn't the EF mapping delete the parent record and set the child ListingID values in MessageThread to null?

Heinrich
  • 1,711
  • 5
  • 28
  • 61

1 Answers1

0

You are unable to delete from this table

dbo.MessageThread", column 'ListingID'

Because you have a Foreign Key to this table

FK_dbo.MessageThread_dbo.Listings_ListingID

Delete the foreign key field value first before you proceed.

or you can do it by Cascading Deletion take a look at this link

Cascading Deletion

Vijunav Vastivch
  • 4,153
  • 1
  • 16
  • 30