.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
相关产品推荐
相关产品推荐

