【问题标题】:DELETE fails with "foreign key constraint failed" even though ON DELETE CASCADE is specified即使指定了 ON DELETE CASCADE,DELETE 也会因“外键约束失败”而失败
【发布时间】:2017-07-26 11:01:35
【问题描述】:

我正在开发 C# 项目,并且正在使用 system.data.sqlite。我创建了 3 个(相关)表

create table students(
    _id integer primary key,
    fname text not null,
    lname text not null,
    st_number integer not null unique,
    level integer not null,
    class integer,
FOREIGN KEY (class) REFERENCES classes(_id) on delete cascade on update cascade,
FOREIGN KEY (level) REFERENCES levels(_id) on delete cascade on update cascade)

create table payments(
    _id integer primary key,
    student integer not null,
    amount integer not null,
    recieve_date text not null,
    type text not null,
foreign key(student) references students(st_number) on update cascade on delete cascade)

create table signups(
    _id integer primary key,
    student integer not null,
    service integer not null,
foreign key(student) references students(st_number) on update cascade on delete cascade,
foreign key(service) references services(_id) on update cascade on delete cascade)

现在,当我尝试从学生表中删除一条记录时,我收到一个 FK 违规错误,而我希望它会从支付和注册表中删除所有连接的条目。

这可能与我在 sqlite 中打开 FK 支持的方式有关。我在我的连接字符串中打开它

@"Data Source=" + dbPath + ";Version=3;foreign_keys = 1;"

抱歉,创建语句太长了。非常感谢任何帮助。

【问题讨论】:

  • I get a FK violation error你能给出exact异常详情吗?
  • @mjwills SQLite 的 FK 约束违规错误消息不包含详细信息。
  • 请提供一些示例数据。 (请参阅How to format SQL tables in a Stack Overflow post? 了解如何添加。)
  • SQLite's error message for a FK constraint violation does not contain details. 能不能提供一下截图?
  • @mjwillis 你的意思是这样想的吗?tinypic.com/r/jhzb4z/9

标签: c# sqlite


【解决方案1】:
@"Data Source=" + dbPath + ";Version=3;foreign_keys = 1;"

看起来是错字,应该改成:

@"Data Source=" + dbPath + ";Version=3;foreign keys = 1;"

我把_改成了一个空格。

【讨论】:

    【解决方案2】:

    原来另一个表指的是付款,它的 FK 没有级联。添加了它,一切正常。

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 2013-04-19
      • 2018-06-10
      • 2019-01-22
      相关资源
      最近更新 更多