SQLite的; "无法添加PRIMARY KEY列"-Exception

Fun*_*nut 7 c# sql

今天我开始处理数据库.我已经安装了SQLite和SQLite-net.我正在使用C#编写Windows 8.1应用程序.

我只有以下几点:

一个模型:

public class Subject
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Name { get; set; }    
}
Run Code Online (Sandbox Code Playgroud)

App.Xaml.cs中的OnLaunched-Event包含:

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
[...]
    // Get a reference to the SQLite database
    DBPath = Path.Combine(
        Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Subjects.s3db");
    // Initialize the database if necessary
    using (var db = new SQLite.SQLiteConnection(DBPath))
    {
        // Create the tables if they don't exist
        db.CreateTable<Subject>();
    }
[...]
}
Run Code Online (Sandbox Code Playgroud)

当我启动它时,我在db.CreateTable()之后得到以下错误; 执行:

无法添加PRIMARY KEY列.

这里出了什么问题?我真的很感激你的帮助.

非常感谢你.

问候,FunkyPeanut

San*_*man 10

我相信这种情况正在发生,因为您通过在Subject类中添加或删除字段来更改数据库表的架构.也就是说Id,在已经运行应用程序来创建Subject表之后,您已经添加了该属性.

这就是为什么它适用于新的DB文件.您需要修改模式(在SQLite中需要创建新表,从现有表复制数据,删除现有表然后重命名新表),或者只是删除旧的DB文件并创建一个新文件.