Bob Gatto
Bob Gatto

Reputation: 115

Key isn't auto-incrementing

I have a view model class setup like this:

using System.ComponentModel.DataAnnotations;

namespace Proj1.Models
{
    public class Groups
    {
        [Key]
        public int Id { get; set; }
        public string? GrpName { get; set; }
    }
}

I thought {Key] had a built in autoincrementing function. So I created a database with three tables like this like this:

var dbfile = GenDbName();    // This generates a database file name.
var dbpath = Path.Combine(datLoc, dbfile);     
var Options = new SQLiteConnectionString(dbpath, true);
var conn = new SQLiteAsyncConnection(Options);

await conn.CreateTablesAsync<LakSettings, Groups, PassWrds>();

And for the Groups table, I added records like this:

var grp = new Groups()
{
    GrpName = "Computer"
};
await conn.InsertAsync(grp);

grp = new Groups()
{
    GrpName = "Email"
};
await conn.InsertAsync(grp);

grp = new Groups()
{
    GrpName = "Internet"
};

await conn.InsertAsync(grp);

And when I look at the Id column of the Group table, each record has the same value of 0.00.

So what's going wrong?

Upvotes: -2

Views: 111

Answers (1)

Fabio Mignone
Fabio Mignone

Reputation: 1

In the class definition, try this syntax for the primary key:

[PrimaryKey, AutoIncrement]
public int Id { get; set; }

This should create the column as unique and auto-incrementing.

Upvotes: 0

Related Questions