eYe
eYe

Reputation: 1733

Create SQLite database using Entity Framework

I am trying to create my first database. I see countless posts on creation being done using existing database and a config file. What I am trying to achieve though, is to create database from code and also do initialization inside code behind, without a config file.

I have the following inside my MyContext class:

   public MyContext() : base("MyDB") 
{
   DatabaseConfiguration _DBConfig = new DatabaseConfiguration();
}

    public DbSet<MyObject> MyObject { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions
            .Remove<PluralizingTableNameConvention>();
    }

Assuming that whenever I create an instance of MyContext, I should get a Database created if such does not exist. But no file gets created.

Initialization is done as following:

class DatabaseConfiguration : DbConfiguration
{
    public DatabaseConfiguration()
        {
            SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
            SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
            SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
        }
}

I am using newest versions of SQLite and EF6 from NuGet.

Upvotes: 1

Views: 3283

Answers (2)

mason
mason

Reputation: 32693

You think you are telling it to use your DatabaseConfiguration, but you're not. Simply declaring a local variable in your constructor doesn't tell the context to use that configuration. You can tell it with the DbConfigurationType attribute.

[DbConfigurationType(typeof(DatabaseConfiguration))] 
public class MyContext : DbContext
{
    public MyContext() : base("MyDB") 
    {
    }

    public DbSet<MyObject> MyObject { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

Upvotes: 2

T N
T N

Reputation: 406

So far as I know, Entity Framework doesn't support creating database + tables for SQLite. You can create a database template by external tool then run manual migrations as suggested in this post for creating or updating database schema.

Upvotes: 0

Related Questions