With the following DB schema:
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));
I created an sqlite database, which I then used to create an Entity Framework .edmx file.
Then I add a master and a slave record, which works fine, and then I try to remove the slave record, but that raises an exception and I don’t know why.
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 message of the exception is:
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.
What am I doing wrong?
Edit:
Here is the generated by EF Createslave(...) method:
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;
}
There is still a slave object in your slave table that has no value set in the masterId column.
Try using
ctx.DeleteObject(newSlave)to get rid of it.