I'm using ASP.NET Core 1.1 with Entity Framework 6 to connect to a SQL Server Compact 3.5 database. How can I configure what provider to use when creating the DbContext
?
MyDbContext.cs
public class MyDbContext: DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// omitted
}
public static DbMasContext Create(string connString)
{
var entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = connString;
entityBuilder.Provider = "System.Data.SqlServerCe.3.5";
return new DbMasContext(entityBuilder.ConnectionString);
}
}
Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddScoped(_ => DbMasContext.Create(Configuration.GetConnectionString("MyDbContext")));
}
// omitted
}
appsettings.json
{
"ConnectionStrings": {
"MyDbContext": "DataSource=C:\\MyDb.sdf;Max Database Size=2048;",
}
}
My code causes this error:
ArgumentException: Keyword not supported: 'provider'
You need to specify the provider in a class that inherits from DbConfiguration
.
SqlCeDbConfiguration
public class SqlCeDbConfiguration: DbConfiguration
{
public DbConfig()
{
SetProviderServices("System.Data.SqlServerCe.3.5", System.Data.Entity.SqlServerCompact.Legacy.SqlCeProviderServices.Instance);
}
}
Then you can apply a DbConfigurationType
attribute to your DbContext
-derived class
MyDbContext.cs
[DbConfigurationType(typeof(SqlCeDbConfiguration))]
public class MyDbContext: DbContext
{
// ...
}