加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:27:24 所属栏目:百科 来源:网络整理
导读:使用以下数据库架构: 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)); 我
使用以下数据库架构:

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)来摆脱它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读