使用以下数据库架构:
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;
}
最佳答案 从属表中仍有一个从属对象在masterId列中没有设置值.
尝试使用ctx.DeleteObject(newSlave)来摆脱它.