简体   繁体   English

EF一对多(可空)删除

[英]EF one to many (nullable) delete

I'm deleting a parent entity in my MVC controller and getting this error: 我正在MVC控制器中删除父实体,并收到此错误:

[SqlException]: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.MessageThread_dbo.Listings_ListingID". [SqlException]:DELETE语句与REFERENCE约束“ FK_dbo.MessageThread_dbo.Listings_ListingID”冲突。 The conflict occurred in database "MyDB", table "dbo.MessageThread", column 'ListingID'. 数据库“ MyDB”的表“ dbo.MessageThread”的列“ ListingID”中发生了冲突。 The statement has been terminated. 该语句已终止。 at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) 在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔值breakConnection,动作1 wrapCloseInAction)

MessageThread table is mapped in EF like this: MessageThread表在EF中的映射如下:

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

The ListingID (parent) column in MessageThread (child) is nullable MessageThread (子级)中的ListingID (父级)列可以为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 ? 根据这个 ,应该不是EF映射删除父记录,并设置孩子ListingID价值观MessageThreadnull

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来实现,请查看此链接

Cascading Deletion 级联删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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