The on delete setting needs to map to the database. Have you updated the database from your edmx model?
Entity Framework Cascade Delete not working
-
22-07-2023 - |
Frage
I have two tables AgentTransmission
and ClearinghousePartners
that share a one to many relationship. Each AgentTransmission
record can serve as a principal for many ClearinhouseParnters
.
This is represented via a List
object in the AgentTransmission
model.
I've sent the OnDelete
property to "Cascade" in the .edmx file, however when I attempt to delete an AgentTransmission
object I'm getting this error.
The DELETE statement conflicted with the REFERENCE constraint
\"FK_ClearinghousePartners_AgentTransmission\". The conflict
occurred in database \"AgentResourcesU01\", table
\"dbo.ClearinghousePartners\", column 'AgtTransId'.\r\nThe
statement has been terminated.
AgentTransmission
This contains a TON of fields so I've reduced it to only those that are relevant to the relationship
public partial class AgentTransmission
{
public int ID { get; set; } //PK
.
.
public virtual List<ClearinghousePartners> ClearinghousePartners { get; set; }
}
Clearinghouse Partners
public partial class ClearinghousePartners
{
public int Id { get; set; }
public string ClearingHouseName { get; set; }
public string TradingPartnerName { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public int AgtTransId { get; set; } //FK
public virtual AgentTransmission AgentTransmission { get; set; }
}
Controller
Nothing crazy here, just doing a normal delete. Would like for the EF to delete all objects in the ClearinghousePartners
List
property of the AgentTransmission
object.. which I believe it is capable of doing (although I could be wrong)
//Cascade deletes set to remove ClearinghousePartners
db.AgentTransmission.Remove(agenttransmission);
db.SaveChanges(); //Exception thrown here
EDMX
Lösung
Andere Tipps
If you are using database first approach, you need to make sure that you configure cascade delete on your database as well.