Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite with Entity Framework

I'm having a problem with primary keys in Entity Framework when using SQLite. SQLite wants an explicit NULL in the VALUES list on an autoincrementing primary key column. I haven't actually looked at the generated SQL in the EF Context, but I believe it's going with the usual SQL Server convention of providing no value for the autoincrementing column.

According to the site for the ADO.NET SQLite provider, EF is fully supported but I'm finding no help there. Is there a way to force EF to explicitly insert a NULL for the primary key value?

like image 501
Dave Swersky Avatar asked Jun 01 '09 21:06

Dave Swersky


People also ask

Can I use Entity Framework with SQLite?

This database provider allows Entity Framework Core to be used with SQLite. The provider is maintained as part of the Entity Framework Core project.

Can I use SQLite with C#?

Open Visual Studio, select new project, and, in Visual C#, select “Console Application” and provide the name as SQLiteDemo. Click OK. To connect SQLite with C#, we need drivers. Install all required SQLite resources from the NuGet package, as pictured in Figure 1.

Does SQLite support migrations?

SQLite does not support this migration operation ('AlterColumnOperation').

Does Visual Studio support SQLite?

The SQL Server Compact & SQLite Toolbox adds several features to help your SQL Server Compact and SQLite development efforts: Explore! Connect to SQL Server Compact 4.0, 3.5, SQL Server and SQLite database files in Visual Studio 2017 and later.


2 Answers

Well I've finally made this work :D. You need to set the id column as autoincrement, this way it does work with EF. Dont ask me why this isnt mentioned in the question about auto-increment in sqlite faq. This is an example:

create table Persona ( PersonaID integer primary key autoincrement, Nombre text) 

Also, I didn't found a way to set this from within visual studio, I had to do it from the command line tool.

UPDATE: The following code works fine.

PruebaDBEntities data = new PruebaDBEntities();          foreach (int num in Enumerable.Range(1, 1000))         {             Persona p = new Persona() { Nombre = "Persona " + num, Edad = num };              data.AddToPersona(p);              data.SaveChanges();              Console.WriteLine(p.PersonaID);         } 

The PersonaID wasn't set, and after the save operation it had the value asigned by sqlite.

like image 120
Pablote Avatar answered Sep 23 '22 02:09

Pablote


Hooray... I've found the solution!

  1. Declare the ID column as INTEGER PRIMARY KEY AUTOINCREMENT in your create table statement. INTEGER PRIMARY KEY won't work!
  2. Update your Entity Framework Model in Visual Studio, set the ID column property StoreGeneratedPattern to "Computed"
like image 45
user371251 Avatar answered Sep 23 '22 02:09

user371251