You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI中如何为ObservableProperty添加SQLite主键自增属性?

解决方案

你预期的写法其实完全可行,CommunityToolkit.Mvvm的源代码生成器会自动将私有字段上的非工具包特性(比如SQLite的[PrimaryKey, AutoIncrement])复制到自动生成的公共属性上。

方案一:直接在字段上添加特性(推荐)

using CommunityToolkit.Mvvm.ComponentModel;
using SQLite;

public partial class YourEntity : ObservableObject
{
    [ObservableProperty]
    [PrimaryKey, AutoIncrement]
    private int id;
}

生成器自动生成的Id属性会带上[PrimaryKey, AutoIncrement]特性,完全满足SQLite的主键自增要求。

方案二:手动声明属性实现通知逻辑

如果遇到特性只能标注在属性上的特殊情况,也可以手动定义属性,借助ObservableObject的SetProperty方法实现属性变更通知,同时直接给属性添加SQLite特性:

using CommunityToolkit.Mvvm.ComponentModel;
using SQLite;

public class YourEntity : ObservableObject
{
    private int id;

    [PrimaryKey, AutoIncrement]
    public int Id
    {
        get => id;
        set => SetProperty(ref id, value);
    }
}

内容的提问来源于stack exchange,提问作者Kioshia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 13:35:19