How to use ON DELETE CASCADE with SQLite and Entity Framework 6

.net c# entity-framework-6 sqlite

Question

With SQLite and Entity Framework 6, I am unable to make DELETE CASCADE ON work (EF6). Do I need to do anything else?

I used Visual Studio 2015 to construct a Windows Forms application in C#. In my application, EF6 and SQLite worked nicely together, allowing me to enter and retrieve data. However, removing a single row or object or an entity in a cascade doesn't function at all. I erased the exact same row with SQLite DB Browser, and the cascade was successful.

The nodes in my table are shown here:

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 removing the "root" node (which is meant to cascade through all child nodes):

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 deleting "root" using the commented version. You can see that I've used a loop to capture all of the root nodes here, but this is unimportant.

For EF6, I'm using a database-first strategy. Please be aware that in order to correct this, I don't want to change any created files.

The following options didn't work for me either:

If you need any extra information, don't hesitate to inquire.

Thanks.

1
0
11/30/2017 9:13:08 AM

Accepted Answer

ZZZ_tmp
0
11/30/2017 9:36:43 AM

Popular Answer

You do not useAsNoTracking I am aware of your question, however you might still try this;

foreach (var root in noParentItems)
{
     entities.Nodes.Attach(root);
     entities.Entry(root).State = EntityState.Deleted;
}

such like this;

foreach (var root in noParentItems)
{
     var newRoot = new Node{ NodeId = root.NodeId };
     entities.Nodes.Attach(newRoot);
     entities.Entry(newRoot).State = EntityState.Deleted;
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow