sqlitemvvmmauicommunity-toolkit-mvvm

Use [PrimaryKey,AutoIncrement] from SQLite in .NET MAUI with [ObservableProperty]


As the title says, I defined my member, for example my Id, as an Observable Property using the CommunityToolKit.Mvvm package.

[ObservableProperty]
private int id;

But now I am trying to decorate my Observable Property with the [PrimaryKey,AutoIncrement] attributes from the SQLite extension. But I can't just write it like that cause we have no self-defined property, only the generated one.

Is there a way to add that annotation while it still is an ObservableProperty?

I Imagine it something like that:

[ObservableProperty]
[PrimaryKey, AutoIncrement]
private int id;

Solution

  • When you need an extra annotation with [ObservableProperty] (that is not part of the toolkit itself), you have to prefix it with "property:".

    So your property could be written like this:

    [ObservableProperty]
    [property: PrimaryKey]
    [property: AutoIncrement]
    private int id;
    

    This way your property will be generated with the [PrimaryKey] and [AutoIncrement] attributes over it.

    See also: https://learn.microsoft.com/dotnet/communitytoolkit/mvvm/generators/observableproperty#adding-custom-attributes