简体   繁体   English

SQLite C#不会插入NULL外键

[英]SQLite C# won't insert a NULL foreign key

I have an issue with adding a NULL value in a Foreign Key column. 我在外键列中添加NULL值时遇到问题。 I have set that the foreign key to be NULLABLE, also I have enabled using foreign keys in C#. 我已将外键设置为NULLABLE,也已在C#中启用了外键。

This is my C# code: 这是我的C#代码:

private static SQLiteConnection _conn = new SQLiteConnection("DataSource = D:/SQLDB.sqlite;foreign keys=true;");
string sql = @"INSERT INTO Scan(id, name, employeeId, scannerId, orderItemId) VALUES (1,'name',1,1,  NULL);";

SQLiteCommand cmd = new SQLiteCommand(sql, _conn);
cmd.ExecuteNonQuery()

I have a table Scan, which has 3 foreign keys employeeId, scannerId and orderItemId. 我有一个表Scan,其中有3个外键employeeId,scannerId和orderItemId。 EmployeeId and ScannerId can not be null, but orderItemId can, because it won't be available until the scan status is finished. EmployeeId和ScannerId不能为null,但orderItemId可以为null,因为在完成扫描状态之前将无法使用它。

The above SQL INSERT cmd throws an exception: 上面的SQL INSERT cmd引发异常:

foreign key mismatch - "Scan" referencing "OrderItem"

I don't understand why, because when I execute the same command in SQLite manually it works fine. 我不明白为什么,因为当我在SQLite中手动执行相同命令时,它可以正常工作。

This is how I created Scan table in SQLite: 这是我在SQLite中创建扫描表的方式:

CREATE TABLE `Scan` (
`id`    INTEGER NOT NULL,
`name`  VARCHAR(255),
`employeeId`    INTEGER NOT NULL,
`scannerId` INTEGER NOT NULL,
`orderItemId`   INTEGER,
PRIMARY KEY(id),
FOREIGN KEY(`employeeId`) REFERENCES `Employee`(`id`),
FOREIGN KEY(`scannerId`) REFERENCES `Scanner`(`id`),
FOREIGN KEY(`orderItemId`) REFERENCES `OrderItem`(`id`)
);

Can you tell me where my mistake/mistakes are? 你能告诉我我的错误/错误在哪里吗? What am I doing wrong? 我究竟做错了什么?

The problem is not the value of the foreign key. 问题不在于外键的值。 (And making a column nullable does not affect other constraints.) (并使列为可空不会影响其他约束。)

The error message "foreign key mismatch" reports errors in the database schema. 错误消息“外键不匹配”报告数据库架构中的错误。 The problem is that you do not have the required index on the OrderItem table. 问题是您在OrderItem表上没有所需的索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM