在一个项目中,我需要设置一个 ASP.NET MVC(使用 .NET 4.6.1),但使用"new"EF Core 来访问数据库。
不幸的是,每个文档都只解释了如何设置 ASP.NET 核心 MVC 项目。
我只是试了一下,当通过包管理器控制台创建数据库时,我收到错误消息:
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'
是的,我没有无参数构造函数,但微软的示例代码也没有
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
我想问题是,我没有在 Startup.cs 中注册 DataContext,而我在“旧”ASP.NET MVC 应用程序中没有。
谁能帮我解决这个问题?
最佳答案
一个简单的例子
在 Example.EF : 安装 EF Core,Microsft 依赖注入(inject)。创建一个类来支持 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);
}
}
在 Example.MVC ,使用 Global.asax 中的 Application_Start 或使用 Owin 启动
// Register services.
IocConfiguration.Configure();
// Example controller
public class ExampleController : Controller
{
private readonly ExampleContext _exampleContext;
public ExampleController(ExampleContext exampleContext)
{
_exampleContext = exampleContext;
}
}
要运行迁移:
Add-Migration {MigrationName} -Project Example.EF -StartupProject Example.Tools
我们应该有 IDesignTimeDbContextFactory 来支持运行迁移。
关于asp.net-mvc-5 - 带有 ASP MVC .NET 4.6 的 EF Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44150727/