c# - 为什么 EntityCollection.Remove() 会导致 SaveChanges() 引发 InvalidOperationException?

标签 c# entity-framework sqlite

使用以下数据库架构:

CREATE TABLE master (
    id integer primary key autoincrement, 
    title text);
CREATE TABLE slave (
    id integer primary key autoincrement, 
    master_id integer not null, 
    title text, 
    foreign key (master_id) references master (id));

我创建了一个 sqlite 数据库,然后我用它来创建一个 Entity Framework .edmx 文件。

然后我添加了一个主记录和一个从记录,它工作正常,然后我尝试删除从记录,但是这引发了一个异常,我不知道为什么。

var ctx = new blaEntities();
var newMaster = master.Createmaster(0);
ctx.masters.AddObject(newMaster);

var newSlave = slave.Createslave(0, 0);
newMaster.slaves.Add(newSlave);

ctx.SaveChanges(); // works fine, both id and master_id properties of newMaster 
                   // and newSlave are then set with generated values.

newMaster.slaves.Remove(newSlave);

ctx.SaveChanges(); // InvalidOperationException is raised

异常信息是:

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.

我做错了什么?

编辑:

这是由 EF Createslave(...) 方法生成的:

public static slave Createslave(global::System.Int64 id, global::System.Int64 master_id)
{
    slave slave = new slave();
    slave.id = id;
    slave.master_id = master_id;
    return slave;
}

最佳答案

在你的slave表中还有一个slave对象在masterId列中没有设置值。

尝试使用 ctx.DeleteObject(newSlave) 来摆脱它。

关于c# - 为什么 EntityCollection.Remove() 会导致 SaveChanges() 引发 InvalidOperationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11309423/

相关文章:

asp.net-mvc - Entity Framework /Glimpse 持续时间差异

sql - 联合所有具有不同列数的查询

c# - Entity Framework .Any() 过滤器出错

c# - 如何从 C++ dll 中删除 C# dll

vb.net - Entity Framework 查询多次返回同一行

sql - "Learn sql the hard way"- 练习 13 : Trouble with a nested select statement

Android 更新所有记录 SQLite

java - 设置为 null 到底有什么作用?

c# - 使用正则表达式进行有限的字符串替换?

visual-studio - VS2012 中缺少 Edmx 设计器和项目模板