I am using Entity Framework Core 2.0 for Sqlite code first in my UWP and .NET Standard app. My model has an entity of type Primary Key integer which should be served as auto increment according to SQLite documentation. But in real for every row that Identity column is getting 0 as a value. Please help because i found no helping material related to this issue.
This is my property without any data annotaion.
public Int32 No { get; set; }
I have used fluent API
modelBuilder.Entity<TurnosGeneral>()
.HasKey(c => new { c.No, c.Cod_Turno });
And value is inserted here
db.TurnosGenerals.Add(new TurnosGeneral { Cod_Turno = numeroTurnoTextBlock.Text });
db.SaveChanges();
For every row inserted c.No is 0.
SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment. The keyword AUTOINCREMENT can be used with INTEGER field only.
In SQLite, an AUTOINCREMENT column is one that uses an automatically incremented value for each row that's inserted into the table. There are a couple of ways you can create an AUTOINCREMENT column: You can create it implicitly when you define the column as INTEGER PRIMARY KEY .
sqlite_sequence. Lists the last sequence number used for the AUTOINCREMENT column in a table. The sqlite_sequence table will only be created once an AUTOINCREMENT column has been defined in the database and at least one sequence number value has been generated and used in the database.
If you don't specify the rowid value or you use a NULL value when you insert a new row, SQLite automatically assigns the next sequential integer, which is one larger than the largest rowid in the table. The rowid value starts at 1. The maximum value of the rowid column is 9,223,372,036,854,775,807 , which is very big.
My model has an entity of type Primary Key integer which should be served as auto increment
The problem is that the property in question is not a PK, but a part of a composite PK, in which case it's not considered as auto generated by convention, as explained in the Generated Values Conventions section of the EF Core documentation:
By convention, non-composite primary keys of type short, int, long, or Guid will be setup to have values generated on add. All other properties will be setup with no value generation.
You need to specify that explicitly:
modelBuilder.Entity<TurnosGeneral>()
.Property(e => e.No)
.ValueGeneratedOnAdd();
Update: The above is the general approach applicable for most of the databases. But SQLite supports AutoIncrement only for column of type INTEGER PRIMARY KEY, hence this is not EF Core limitation. Either don't use auto increment or make it non-composite PK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With