与级联问题删除使用实体框架和System.Data.SQLite实体、框架、级联、问题

2023-09-02 01:48:48 作者:官方小可爱

我有一个设置,以便当我删除一个Person删除级联一个SQLite数据库。这工作得很好,当我手动删除一个Person(引用PERSONID的所有记录都被删除)。但是,当我使用实体框架删除的人,我得到一个错误:

System.InvalidOperationException:操作失败:关系无法改变,因为一个或一个以上的外键的属性是不可为空。当做出改变有关系,相关的外键属性设置为空值。如果外键不支持空值,一个新的关系必须定义,外键属性必须指定一个非空值,或者不相关的对象必须被删除。

我不明白这是为什么发生。我的触发设置清理删除它被告知删除对象之前,所有相关的对象。

当我去到模型编辑器,并检查相关的属性就显示了OnDelete财产采取任何行动。为什么不是这个正确设置从数据库中拉了吗?如果我更改此值级联一切工作正常,但我宁愿不要依赖此手动更改,因为如果我刷新我的模型从数据库中,它失去了。

下面是relivent SQL为我的表。

  CREATE TABLE [SomeTable]
(
    [SomeTableID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    [PERSONID] INTEGER NOT NULL参考文献:[人](PERSONID)ON DELETE CASCADE
)
CREATE TABLE [人]
(
    [PERSONID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT
)
 

解决方案

我刚刚处理了这个确切的问题。原来,当我用EF从数据库更新模型... 选项,它没有正确地得到瀑布规则上删除。

尝试将您的EF数据库模型,单击引起问题的关联,然后确保了 END1 OnDelete (可能是END2,取决于数据库模式)设置为级联

C 操作SQLite数据库的经验汇总

I have a SQLite DB that is set up so when I delete a Person the delete is cascaded. This works fine when I manually delete a Person (all records that reference the PersonID are deleted). But when I use Entity Framework to delete the Person I get an error:

System.InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

I don't understand why this is occurring. My trigger is set to clean up all related objects before deleting the object it was told to delete.

When I go into the model editor and check the properties of the relationship it shows no action for the OnDelete property. Why isn't this set correctly by pulling it from the DB? If I change this value to Cascade everything works properly, but I would rather not rely on this manual change because what if I refresh my model from the DB and it looses that.

Here's the relivent SQL for my tables.

CREATE TABLE [SomeTable] 
(
    [SomeTableID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    [PersonID] INTEGER NOT NULL REFERENCES [Person](PersonID) ON DELETE CASCADE
)
CREATE TABLE [Person]
(
    [PersonID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT
)

解决方案

I just dealt with this exact issue. It turned out that when I used EF to Update model from database... option, it didn't properly get the "Cascade" rule for on delete.

Try going to your EF database model, click the association that is causing the problem, then make sure that the End1 OnDelete (could be End2, depends on database scheme) is set to Cascade.