简体   繁体   中英

SQLite C# won't insert a NULL foreign key

I have an issue with adding a NULL value in a Foreign Key column. I have set that the foreign key to be NULLABLE, also I have enabled using foreign keys in C#.

This is my C# code:

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. EmployeeId and ScannerId can not be null, but orderItemId can, because it won't be available until the scan status is finished.

The above SQL INSERT cmd throws an exception:

foreign key mismatch - "Scan" referencing "OrderItem"

I don't understand why, because when I execute the same command in SQLite manually it works fine.

This is how I created Scan table in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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