问题
I have very simple relationship, my model looks like this:
public class Project
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
[ForeignKey(typeof(User))]
public int ProjectManagerID { get; set; }
[ManyToOne]
public User ProjectManager { get; set; }
}
public class User
{
public string Login { get; set; }
[OneToMany]
public List<Project> Projects { get; set; }
}
The problem is that I can easly save project, with its reference to user without saving user, and I don't get any constraint violation exception.
database.Insert(new Project
{
Name = "aaa",
ProjectManagerID = 8
});
I can even query my project, with invalid user id, but I don't have any record in User table stored. Another interesting thing is that I cannot store row like the one above in my SQLite management tool when I open this database, so I am sure my database schema is ok.
Is this normal in sqlite-net PCL library with sqlite-net-extensions?
UPDATE: My sqlite version is 3.8.7.4
回答1:
Yes, it is normal. SQLite-Net Extensions is built on top of SQLite-Net, that doesn't have support for foreign key constraints, so there's no foreign key declared at the database layer.
Using core SQLite-Net methods, the [ForeignKey]
property is just an integer property that doesn't have any kind of restriction, so you can modify it at will without runtime errors.
If your project requires foreign key constraints at database layer, you could use Execute
method to add the constraints to the columns that you want manually.
UPDATE:
Foreign keys are disabled by default in SQLite. To enable foreign keys in SQLite-Net, you have to add the following code to the beginning of your program. This statement is not persisted in the database and must be executed every time the application starts:
database.Execute("PRAGMA foreign_keys = ON");
To check that it's enabled, you can use PRAGMA foreign_keys
:
int result = database.ExecuteScalar<int>("PRAGMA foreign_keys");
if (result == 1) {
// Foreign keys enabled
}
After it's enabled, you can add foreign keys to your tables declarations (sqlite doesn't support adding constraints on ALTER statements) like this:
CREATE TABLE child (
id INTEGER PRIMARY KEY,
parent_id INTEGER,
description TEXT,
FOREIGN KEY (parent_id) REFERENCES parent(id)
);
Obviously creating the tables manually forces you to not use SQLite-Net CreateTable
statements.
回答2:
Problem solved. I forgot to copy my database from Resources folder (as template) to app data folder, so technically my databse was being created by SQLite-Net, without any foreign keys. Thanks for help
来源:https://stackoverflow.com/questions/28408073/manytoone-constraint-not-working