简体   繁体   English

实体框架不级联删除

[英]Entity Framework not cascade deleting

In short EF default is to delete cascade. 简而言之,EF默认是删除级联。 I have a parent/child relationship I set up using Entity Developer by Devart. 我有一个使用Devart的Entity Developer设置的父/子关系。 It is set to delete cascade. 设置为删除级联。 The parent table looks like this: 父表如下所示:

CREATE TABLE `Tools` (
`ToolNumber`    TEXT,
`ToolID`    INTEGER PRIMARY KEY AUTOINCREMENT
);

The child table has the following definition: 子表具有以下定义:

CREATE TABLE `FirstParts` (
`FirstPartID`   INTEGER PRIMARY KEY AUTOINCREMENT,
`DateTime`  TEXT,
`ToolID`    INT32 NOT NULL,
CONSTRAINT `FK_FirstParts_Tools` FOREIGN KEY(`ToolID`) REFERENCES 
`Tools`(`ToolID`) ON DELETE CASCADE
);

I can add records to the parent/child by using the following code. 我可以使用以下代码将记录添加到父/子中。 When I use this I DO get a record in each table and the ToolID is set correctly. 当我使用它时,我确实在每个表中都有一条记录,并且正确设置了ToolID。

using (var context = new Entities())
{
    var query = from t in context.Tools
                        where t.ToolNumber == "Hello"
                        select t;

    if (!query.Any())
    {
          var tool = new Tool()
                     {
                        ToolNumber = "Hello",
                        FirstParts = new System.Data.Entity.Core.Objects.DataClasses.EntityCollection<FirstPart>() { new FirstPart() { DateTime = "Same text" } }
                   };

        context.AddToTools(tool);
        context.SaveChanges();
    }
}

When I use the following to delete the parent the child is left hanging: 当我使用以下命令删除父母时,孩子被吊死了:

 using (var context = new Entities())
 {
     var query = (from t in context.Tools
                         select t).FirstOrDefault();

     if (query != null)
     {
        context.Tools.DeleteObject(query);
        context.SaveChanges();
     }
}

If I use SQLite Browser and do the following SQL then both parent and child gets deleted properly So I know it is not SQLite. 如果我使用SQLite浏览器并执行以下SQL,那么父级和子级都会被正确删除,因此我知道它不是SQLite。

DELETE FROM Tools WHERE Tools.ToolID = 6;

I have looked for the following to make sure Cascade delete is not getting overridden: 我一直在寻找以下内容,以确保级联删除不会被覆盖:

OnModelCreating(false)

It is not present in the code created by Entity Developer. 它不在实体开发人员创建的代码中。

What could be causing EF to not cascade delete? 是什么导致EF无法级联删除?

Please add "Foreign Key Constraints=On;" 请添加“ Foreign Key Constraints = On;”。 to your connection string to fix the issue. 您的连接字符串以解决此问题。 Refer to https://www.devart.com/dotconnect/sqlite/docs/?Devart.Data.SQLite~Devart.Data.SQLite.SQLiteConnection~ConnectionString.html . 请参阅https://www.devart.com/dotconnect/sqlite/docs/?Devart.Data.SQLite~Devart.Data.SQLite.SQLiteConnection~ConnectionString.html

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

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