简体   繁体   中英

EF one to many (nullable) delete

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM