Let's say I have a database with table A and table B. B has a foreign key to table A, which does not allow nulls. When I try to delete and entity of A I want all references in table B to be removed as well. I try to do this with the following code:
using (var ctx = new MyDatabaseContext(ConnectionString))
{
var a= new A() { IdA= idA};
ctx.A.Attach(a);
ctx.A.Remove(a);
ctx.SaveChanges();
}
This results in the following error message:
Additional information: The DELETE statement conflicted with the REFERENCE constraint "FK_B_A". The conflict occurred in database "MyDatabase", table "dbo.B", column 'IdA'.
The statement has been terminated.
I have tried a lot, from using Triggers in the database to defining the ON DELETE CASCADE, but Entity Framework does fail. What am I doing wrong?
Trigger:
ALTER TRIGGER [dbo].[trg_DelA]
ON [dbo].[A]
FOR DELETE AS
BEGIN
DELETE FROM B WHERE B.IdA = IdA;
END
BTW: This is just an example. The actual database is larger and also contains intermediate tables for many to many relationships.
BR Thomas