如何使用 SQLite-net 为 SQLite 中的列设置默认值

本文关键字:设置 默认值 SQLite 何使用 SQLite-net | 更新日期: 2023-09-27 18:30:17

我正在将Android代码导入Windows rt,我需要数据在两个应用程序上兼容。创建我的 sqlite 数据库时,我需要为列设置默认值,执行类似

CREATE TABLE [blabla] ( [id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [bleh] INTEGER NOT NULL DEFAULT -1 )

我用SQLite-net编写了我的C#代码,这样:

[Table("blabla")]
public class Blabla {
    [PrimaryKey, AutoIncrement, NotNull]
    public int id { get; set; }
    [NotNull]
    public int bleh { get; set; }
}

但是我无法将默认值设置为"bleh"。我需要两个数据库相同=/谁能帮我解决这个问题?

谢谢=)

如何使用 SQLite-net 为 SQLite 中的列设置默认值

为什么不使用:

    private int _bleh = 1;
    [NotNull]
    public int Bleh
    {
        get { return _bleh; }
        set { _bleh = value; }
    }

则 bleh 将始终具有默认值 1,除非更改

只要没有得到答案,我就使用 SQL 语句创建了整个数据库,因此不需要由我的 C# 代码创建数据库。它工作正常!

我知道

已经晚了,但也许这会帮助像我这样的人。如果您的 SQLite 支持Default,请使用Default属性

[Table("blabla")]
public class Blabla {
    [PrimaryKey, AutoIncrement, NotNull]
    public int id { get; set; }
    [NotNull,Default(value:1)]
    public int bleh { get; set; }
}

如果您的 SQLite 不支持Default,您可以简单地分配默认值,如下所示:

 [Table("blabla")]
    public class Blabla {
        [PrimaryKey, AutoIncrement, NotNull]
        public int id { get; set; }
        [NotNull]
        public int bleh { get; set; } = 1;
    }

我总是喜欢第二种方式。