I can't get ON DELETE CASCADE work with SQLite and Entity Framework 6 (EF6). Is there anything I'm missing?
I created a Windows Forms application in C# with Visual Studio 2015. EF6 and SQLite were well working together in my application, I could insert and retrieve data. But when it comes to delete stuff, deleting one row/entity works fine but the cascade doesn't work at all. With DB Browser for SQLite, I deleted the exact same row, and the cascade worked.
This is my table which represents nodes:
CREATE TABLE `Nodes` (
`NodeId` INTEGER,
`ParentId` INTEGER,
`Label` TEXT,
PRIMARY KEY(`NodeId`),
FOREIGN KEY(`ParentId`) REFERENCES `Nodes`(`NodeId`) ON DELETE CASCADE
);
And this is how I'm deleting the "root" node (supposed to delete every child nodes with cascade):
var noParentItems = entities.Nodes.Where(n => n.ParentId == null);
foreach (var root in noParentItems)
{
//entities.Entry(root).State = EntityState.Deleted;
entities.Nodes.Remove(root);
}
entities.SaveChanges();
Notes: I also tried the commented version to delete "root". Here you see that I am looping to catch every root nodes, but this is not important.
I am using the database-first approach for EF6. Please note that I don't want to modify any generated file to fix this.
Also, these solutions didn't work for me:
- Entity Framework On Delete Cascade when entity is loaded : nothing changed
- Put "cascade" in the designer ( How to delete a row with data with its parent row in another table ) : nothing changed
- Use "entities.Nodes.Attach(root);" as suggested in one of the answer below didn't work either
Please feel free to ask any additional information you may need.
Thanks.