如何为具有 Xamarin 中使用的 SQLITE 版本的列设置默认值



我正在我的Xamarin应用程序中创建一个SQLITE表,如下所示:

public class ClickHistory
{
    [PrimaryKey, NotNull]
    public string Yymmdd { get; set; }
    public int DayOfYear { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
    public int BtnACount { get; set; }
    public int BtnBCount { get; set; }
    public int BtnCCount { get; set; }
    public int BtnDCount { get; set; }
}
db2.CreateTable<ClickHistory>();

有人可以帮助我,告诉我如何将BtnACount,BtnBCount,BtnCCount,BtnDCount列的默认值设置为0。 现在,当我进行插入但不指定这些列时,它默认为 null。

请注意另一个问题中建议的解决方案,有人为我标记为重复:

[NotNull, Default(value: true)]

在带有 Xamarin 的 SQLITE 版本中不起作用

如果您的 SQLite 支持默认,则使用默认属性

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

如果您的 SQLite 不支持默认值,您可以像这样简单地分配默认值:

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

我更喜欢第二种方式。

最新更新