In a project I need to set up an ASP.NET MVC (with .NET 4.6.1) but using the "new" EF Core for accessing the database.
Unfortunately every documentation explains only how to setup an ASP.NET Core MVC project.
I just gave it a try and when it comes to creating the database via the Package Manager Console I get the error message:
No parameterless constructor was found on 'DataContext'. Either add a parameterless constructor to 'DataContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'DataContext'
Yes, I don't have a parameterless constructor but neither does the example code of microsoft
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
I guess the problem is, that I don't register the DataContext in the Startup.cs which I don't have in an "old" ASP.NET MVC application.
Can anyone help me with this one?
A simple example
In Example.EF: Install EF Core, Microsft Dependency Injection. Create a class to support DI
public static class IocConfiguration
{
public static void Configure()
{
var services = new ServiceCollection();
services.AddDbContextPool<ExampleContext>(options => {
options.UseSqlServer("_connectionstring_");
});
// Register to support the ExampleController can get DbContext.
services.AddTransient(typeof(ExampleController));
var serviceProvider = services.BuildServiceProvider();
DependencyResolver.SetResolver(new DefaultServiceResolver(serviceProvider));
}
}
public class DefaultServiceResolver : IDependencyResolver
{
private readonly IServiceProvider _serviceProvider;
public DefaultServiceResolver(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public object GetService(Type serviceType)
{
return _serviceProvider.GetService(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _serviceProvider.GetServices(serviceType);
}
}
In the Example.MVC, with the Application_Start in Global.asax or Startup with Owin
// Register services.
IocConfiguration.Configure();
// Example controller
public class ExampleController : Controller
{
private readonly ExampleContext _exampleContext;
public ExampleController(ExampleContext exampleContext)
{
_exampleContext = exampleContext;
}
}
To run the migration:
Add-Migration {MigrationName} -Project Example.EF -StartupProject Example.Tools
We should have IDesignTimeDbContextFactory to support to run the migration.