Reputation: 1733
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
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