I'm trying to create a base dbcontext that contains all the common entities that will always be reused in multiple projects, like pages, users, roles, navigation etc.
In doing so I have a ContextBase class that inherits DbContext and defines all the DbSets that I want. Then I have a Context class that inherits ContextBase where I define project specific DbSets. The classes are defined as follows:
public class ContextBase : DbContext
{
public virtual DbSet<User> Users { get; set; }
//more sets
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UsersConfiguration());
//add more configurations
}
}
public class Context : ContextBase
{
public DbSet<Building> Buildings { get; set; }
//some more project specific sets
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new BuildingsConfiguration());
//add more project specific configs
}
}
In my global.asax:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
where Configuration referes to a class inheriting DbMigrationsConfiguration and overriding the Seed method.
The two context classes are defined in the same namespace, but cross assembly (in order that I may update the base project in multiple existing projects without touching the project specific code) - not sure if this is relevant.
MY PROBLEM:
When running this code, it works fine, but when looking in the Database, it actually creates two different databases!! One containing all the base entity tables and one containing BOTH base and custom tables. CRUD operations are only performed on the custom version (which is obviousely what I want), but why does it create the schema of the other one as well?
Any help is appreciated, thanks!
UPDATE:
The following code is what I ended up with. It isn't ideal, but it works. I would still love to get feedback on ways to improve this, but in the meantime I hope this helps further the process. I REALLY DO NOT RECOMMEND DOING THIS! It is extremely error prone and very frustrating to debug. I'm merely posting this to see if there is any better ideas or implementations to achieve this.
One (but not the only) issue still existing is that the MVC views have to be manually added to projects. I've added it to the Nuget package, but it takes 2 to 3 hours to apply a nuget package with so many files when VS is connected to TFS. With some more work and a custom View engine the views can be precompiled (http://blog.davidebbo.com/2011/06/precompile-your-mvc-views-using.html).
The solution is split into the Base Framework projects and the Custom projects (each category includes its own models and repository pattern). The framework projects are packaged up in a Nuget package and then installed in any custom projects allowing the common functionality of any project like user, role and permission management, content management, etc (often referred to as the Boiler Plate) to be easily added to any new projects. This allows any improvements of the boilerplate to be migrated in any existing custom projects.
Custom Database Initializer:
public class MyMigrateDatabaseToLatestVersion : IDatabaseInitializer<Context>
{
public void InitializeDatabase(Context context)
{
//create the base migrator
var baseConfig = new FrameworkConfiguration();
var migratorBase = new DbMigrator(baseConfig);
//create the custom migrator
var customConfig = new Configuration();
var migratorCustom = new DbMigrator(customConfig);
//now I need to check what migrations have not yet been applied
//and then run them in the correct order
if (migratorBase.GetPendingMigrations().Count() > 0)
{
try
{
migratorBase.Update();
}
catch (System.Data.Entity.Migrations.Infrastructure.AutomaticMigrationsDisabledException)
{
//if an error occured, the seed would not have run, so we run it again.
baseConfig.RunSeed(context);
}
}
if (migratorCustom.GetPendingMigrations().Count() > 0)
{
try
{
migratorCustom.Update();
}
catch (System.Data.Entity.Migrations.Infrastructure.AutomaticMigrationsDisabledException)
{
//if an error occured, the seed would not have run, so we run it again.
customConfig.RunSeed(context);
}
}
}
}
Framework's DB Migrations Configuration:
public class FrameworkConfiguration: DbMigrationsConfiguration<Repository.ContextBase>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
public void RunSeed(Repository.ContextBase context)
{
Seed(context);
}
protected override void Seed(Repository.ContextBase context)
{
// This method will be called at every app start so it should use the AddOrUpdate method rather than just Add.
FrameworkDatabaseSeed.Seed(context);
}
}
Custom Project's DB Migrations Configuration:
public class Configuration : DbMigrationsConfiguration<Repository.Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
public void RunSeed(Repository.Context context)
{
Seed(context);
}
protected override void Seed(Repository.Context context)
{
// This method will be called at every app start so it should use the AddOrUpdate method rather than just Add.
CustomDatabaseSeed.Seed(context);
}
}
The custom DbContext
//nothing special here, simply inherit ContextBase, IContext interface is purely for DI
public class Context : ContextBase, IContext
{
//Add the custom DBsets, i.e.
public DbSet<Chart> Charts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//Assign the model configs, i.e.
modelBuilder.Configurations.Add(new ChartConfiguration());
}
}
Framework DbContext:
//again nothing special
public class ContextBase: DbContext
{
//example DbSet's
public virtual DbSet<Models.User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder);
}
In the global.asax AppStart:
//first remove the base context initialiser
Database.SetInitializer<ContextBase>(null);
//set the inherited context initializer
Database.SetInitializer(new MyMigrateDatabaseToLatestVersion());
In the web.config:
<connectionStrings>
<!--put the exact same connection string twice here and name it the same as the base and overridden context. That way they point to the same database. -->
<add name="Context" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=CMS2013; Integrated Security=SSPI;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient"/>
<add name="ContextBase" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=CMS2013; Integrated Security=SSPI;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
(from the comments)
You're creating ContextBase objects directly, apparently as new T() in a generic method with ContextBase as a generic type argument, so any initialisers for ContextBase also run. To prevent creating ContextBase objects (if it should never be instantiated directly, if the derived context should always be used), you can mark the class as abstract.
Your ContextBase seems to have an initializer as well.. You can remove this by
Database.SetInitializer<ContextBase>(null);
Related
I want to use EF.Core 2.2.6 in a .Net Framework (4.6.2) project. I have created a separate project for the database.
I want to register the DbContext in the main project using dependency injection over the Prism framework (Unity).
var optionsBuilder = new DbContextOptionsBuilder<DbContext>();
optionsBuilder.UseSqlite(#"Data Source=CustomerDB.db");
containerRegistry.GetContainer().RegisterType<DbContext, CrossSettingContext>();
containerRegistry.GetContainer().RegisterType<DbContext>(new InjectionConstructor(optionsBuilder));
The database context:
public class CrossSettingContext : DbContext
{
private static Action<DbContextOptionsBuilder> onConfigure;
#pragma warning restore 649
public CrossSettingContext(DbContextOptions<CrossSettingContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.EnableSensitiveDataLogging(true);
onConfigure?.Invoke(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Setting>().Map();
}
}
I get the following exception. The question is if I am using the right approach for registering EF Core.
System.InvalidOperationException: "No member matching data has been found.
Error in: RegisterType(Invoke.Constructor(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder`1[Microsoft.EntityFrameworkCore.DbContext]))
I found this question -> but I need EF Core 2.2.6 and not Entity Framework 6.0
The answer from Haukinger is partially correct, but missing quite a bit of important information.
What you will want to do something like:
var optionsBuilder = new DbContextOptionsBuilder<CrossSettingContext>();
optionsBuilder.UseSqlite( #"Data Source=CustomerDB.db" );
However you do not need anything Container Specific AT ALL here. All you really need is:
containerRegistry.RegisterInstance(optionsBuilder.Options);
You do not actually need to register the CrossSettingContext if you want a new instance each time it's resolved. Though you could do the following if you want a singleton:
containerRegistry.RegisterSingleton<CrossSettingContext>();
When you want to use it you can just inject the context in your ViewModel/Services like:
public class ViewAViewModel
{
public ViewAViewModel(CrossSettingContext context)
{
// Do Stuff
}
}
I have a project with multiple DbContext classes: one for every domain. Since EF Core isn't perfect I have some functionality I have to add to every DbContext like allowing it to handle the new JSON functionality of SQL Server 2017. There is other functionality I'm adding too but for the sake of brevity I have removed it from the example.
To add this JSON functionality to every DbContext I work with a BaseDbContext which is an abstract class that simply extends the DbContext. One of the prerequisites for the functionality is interception of SQL queries that are sent to the database. To perform this I make use of the tactic described here.
In the next few weeks we are moving into different development environments and I want to inject the correct connection string based on the current environment through the Options pattern. This doesn't play well with the interception tactic. Since to perform interception GetService<DiagnosticSource>() is called which actually triggers the OnConfiguring function BEFORE the continuation of the constructor of my SomeDbContext, which means my options are never filled in leading to a NullReferenceException.
How can I extend DbContext without triggering OnConfiguring while at the same time avoiding code duplication? I can also run a custom EF Core but I'd like to avoid that if at all possible.
public abstract class BaseDbContext : DbContext, IBaseDbContext
{
protected BaseDbContext()
{
DiagnosticListener listener = this.GetService<DiagnosticSource>() as DiagnosticListener; // This calls OnConfiguring.
listener.SubscribeWithAdapter(new JsonInterceptor());
}
[DbFunction("JSON_VALUE", "")]
public static string JsonValue(string source, string path)
{
throw new NotSupportedException();
}
[DbFunction("TRY_CAST", "")]
public static string TryCast(string source, string typeName)
{
throw new NotSupportedException();
}
}
public class SomeDbContext : BaseDbContext, ISomeDbContext
{
private readonly SomeDbContextOptions _options;
public DbSet<Order> Orders { get; set; }
public SomeDbContext(IOptions<SomeDbContextOptions> options)
{
_options = options.Value;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// This is called before _options is set meaning it is null in the line below.
optionsBuilder
.UseSqlServer(_options.ConnectionString);
}
}
I'm trying to use Ef Core in my project.
The structure is a little different, in the sense that I'm not using EfCore insite the WebApi.csproj. In fact I have a different dll. and a DependenciesResolver.dll that handles all my dependency injection.
In my EfCore.dll I've installed both
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Now when I try to run the command (the dll in which I'm running is the EfCore.dll)
Add-Migration Name
I get this :
An error occurred while accessing the IWebHost on class 'Program'.
Continuing without the application service provider. Error: Object
reference not set to an instance of an object. Unable to create an
object of type 'StoreContext'. Add an implementation of
'IDesignTimeDbContextFactory' to the project, or see
https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns
supported at design time.
The structure of the sln is like this
WebApi | EfCore.dll | DependencyResolver.dll and I want to keep it this way, don't want to permit using EfCore in my WebApi.
What is the resolution for this issue ?
If this helps within the EfCore.dll I have this.
public sealed partial class StoreContext : DbContext, IStoreContext
{
private string _connectionString;
public StoreContext(string connectionString) : base()
{
_connectionString = connectionString;
Database.EnsureCreated();
}
/// db.tbls
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddOrderConfiguration();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
}
which is called by DependencyResolver like this
private DependenciesResolver RegisterInfrastructure()
{
_serviceCollection.AddScoped<StoreContext>(factory => new StoreContext(_connectionString));
return this;
}
and the DependencyResolver is then called by the WebApi
Please have a look at this: https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
The error message clearly specifies the EF Core tools can't create an instance of your Context at design-time.
If you can define a constructor with no parameters for your StoreContext that would work, otherwise you need tell the tools how to create an instance of your context at design-time by defining a class that implements the IDesignTimeDbContextFactory interface.
I created a web starter application with VS 2015 ctp, and I would like to add an in-memory store to do some test, but when I try to read the data, I get this message
The data stores 'SqlServerDataStore' 'InMemoryDataStore' are
available. A context can only be configured to use a single data
store. Configure a data store by overriding OnConfiguring in your
DbContext class or in the AddDbContext method when setting up
services.
How can I do to create a second datastore? Now I have this row in the ConfigureService method
AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<ApplicationDbContext>()
.AddInMemoryStore()
.AddDbContext<WorkModel>( options => { options.UseInMemoryStore(persist: true); });
Edit:
Looks like the scenario is not clear.
I have the identy sql server dbcontext, and I want to add a second dbcontext, totally separated, that I want to run in memory. I'm looking how configure two different dbcontext, in this case using two different datastores.
The first one is the Identity ApplicationDbContext, and another is something like this:
public class WorkModel : DbContext
{
public DbSet<Cliente> Clienti { get; set; }
public DbSet<Commessa> Commesse { get; set; }
protected override void OnModelCreating(ModelBuilder builder) {
builder.Entity<Cliente>().Key(cli => cli.ClienteId);
builder.Entity<Commessa>().Key(cli => cli.CommessaId);
}
}
Or whatever custom dbcontext do you like
It's possible use one DbContext type with multiple data stores. It won't however play well with your calls to .AddDbContext(). Here is an example of how to do it taking .ConfigureServices() entirely out of the picture.
class MyContext : DbContext
{
bool _useInMemory;
public MyContext(bool useInMemory)
{
_useInMemory = useInMemory;
}
protected override void OnConfiguring(DbContextOptions options)
{
if (_useInMemory)
{
options.UseInMemoryStore(persist: true);
}
else
{
options.UseSqlServer();
}
}
}
You can then instantiate your context specifying which provider to use.
var inMemoryContext = new MyContext(useInMemory: true);
var sqlServerContext = new MyContext(useInMemory: false);
You probably need to do something like this instead...
// Add first DbContext here
AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<ApplicationDbContext>();
// Add second DbContext here
AddEntityFramework(Configuration)
.AddInMemoryStore()
.AddDbContext<WorkModel>(options => { options.UseInMemoryStore(persist: true); });
In my case, when I needed to create two SQL Contexts, I had to do this...
AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<ApplicationDbContext>()
.AddDbContext<AnotherDbContext>();
In my case, I'm using Entity Framework Core 1.0.1 with ASP.NET Core 1.0.1 and I want to run the same project on Windows and OS X but with different databases. So this is working for me:
Added some logic in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("WindowsConnection")));
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("OSXConnection")));
}
}
Then defined the two different connection strings in appsettings.json:
"ConnectionStrings":
{
"WindowsConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-{dbname}-{dbguid};Trusted_Connection=True;MultipleActiveResultSets=true",
"OSXConnection": "Data Source=\/Users\/{username}\/Documents\/{projectname}\/bin\/debug\/netcoreapp1.0\/{dbname}.db"
}
And added this logic to ApplicationDbContext.cs:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
optionsBuilder.UseSqlite("Filename=./{dbname}.db");
}
}
If you're dbcontext has
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(<connection string>);
}
then you can avoid the double configuration by adding a guard
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if(!optionsBuilder.IsConfigured){
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(<connection string>);
}
}
and then have a class that extends your DBContext which uses the inmemory provider, and you instantiate explicitly for your tests. Then you can pass in to the target classes, and avoid the double provider issue.
I am starting a vNext project, and I'm having some issues kicking it off the ground. I have added a table to the ApplicationDbContext class, and it successfully created the table in the db (which in my case is in Azure). However, I can't seem to correctly instantiate a dbContext to use in my Controllers.
In my experience with previous ASP.NET EF projects, I could instantiate the ApplicationDbContext class without passing it any parameters, but in the case of vNext however, it seems to expect a number of things (IServiceProvider, and IOptionsAccessor<DbContextOptions>). I have tried creating a parameter-less constructor, but the App breaks due to not knowing what connection strings to use. My code is below -- as you see in the OnConfiguring(DbContextOptions options) override, I force the connection string in via the DbContextOptions, but that's obviously not ideal, and I feel like I'm just not understanding where those two IServiceProvider, and IOptionsAccessor parameters need to come from.
Thanks for any help!
namespace Project.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public string CompanyName { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private static bool _created = false;
public DbSet<Business> Businesses { get; set; }
public ApplicationDbContext()
: base()
{
if (!_created)
{
Database.EnsureCreated();
_created = true;
}
}
protected override void OnConfiguring(DbContextOptions options)
{
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();
options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
}
public ApplicationDbContext(IServiceProvider serviceProvider, IOptionsAccessor<DbContextOptions> optionsAccessor)
: base(serviceProvider, optionsAccessor.Options)
{
// Create the database and schema if it doesn't exist
// This is a temporary workaround to create database until Entity Framework database migrations
// are supported in ASP.NET vNext
if (!_created)
{
Database.EnsureCreated();
_created = true;
}
}
}
}
IServiveProvider and IOptionAccessor are injected by the Dependency Injection
the ASP.Net Core DI has limitation, you cannot have more than one constructor.
Read this: http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx