SQLite with EntityFramework with Code-First

c# ef-code-first entity-framework sqlite system.data.sqlite


I'm attempting to use the EF to automatically generate an embedded SQLite database, but I'm having trouble since the database file never gets built.

I have SQLite version 10.0 and EF 4.2.

What I have is this


<?xml version="1.0"?>
      <remove invariant="System.Data.SQLite"/>
      <add name="SQLite Data Provider"
           description=".Net Framework Data Provider for SQLite"
           type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite"/>
    <add name="DataContext"
         connectionString="Data Source=test.db;Version=3;New=True;"
         providerName="System.Data.SQLite" />
    <supportedRuntime version="v4.0" />

Initializing DB (to put some content in)

class PageDbInitializer : DropCreateDatabaseAlways<PageDB>
    protected override void Seed(PageDB context)
        for (int i = 0; i < 10; i++)
            WebPage page = new WebPage() { Name = "Page" + (i + 1) };


class PageDB : DbContext
        public DbSet<WebPage> Pages { get; set; }

And lastly, in general ()

Database.SetInitializer( new PageDbInitializer() );

I think I'm missing certain stages, but I can't figure out which ones.

7/23/2012 8:01:29 PM

Accepted Answer

System.Data.SQLite is currently the only provider that is EFv1 compliant (1, 2). It denotes the absence of EFv4 functionalities like database creation and deletion (check; EFv4.2 is a wrapper over EFv4).DbProviderServices MSDN contains changes between.NET 3.5 and.NET 4.0). Because of this, while using SQLite, automated database creation with code first is not possible. All tables and the database must be manually created.

You may use a different SQLite supplier as an option. For instance, SQLite from Devart providesr asserts that it enables the construction of databases using EFv4 and 4.1.

12/14/2011 7:06:17 PM

Popular Answer

Look at this:


Additionally offered as a NuGet

Your project gains various DB Initializers thanks to it, includingSqliteCreateDatabaseIfNotExists

Here is an example of a website:

public class MyDbContext : DbContext
    public MyDbContext()
        : base("ConnectionStringName") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<MyDbContext>(
            Database.Connection.ConnectionString, modelBuilder);

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow