Bab*_*sus 6 asp.net-mvc-5 entity-framework-core
在一个项目中,我需要设置一个ASP.NET MVC(带有.NET 4.6.1),但是要使用“新” EF核心访问数据库。
不幸的是,每个文档都只解释了如何设置ASP.NET Core MVC项目。
我只是尝试了一下,当通过Package Manager Console创建数据库时,出现错误消息:
在“ DataContext”上找不到无参数的构造函数。在“ DataContext”中添加无参数构造函数,或者在与“ DataContext”相同的程序集中添加“ IDbContextFactory”的实现
是的,我没有无参数的构造函数,但是Microsoft的示例代码也没有
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
我想问题是,我没有在“旧” ASP.NET MVC应用程序中没有的Startup.cs中注册DataContext。
有人可以帮我吗?
小智 6
一个简单的例子
在Example.EF 中:安装 EF Core,Microsft 依赖注入。创建一个类来支持 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);
}
}
Run Code Online (Sandbox Code Playgroud)
在Example.MVC 中,使用 Global.asax 中的 Application_Start 或 Startup with Owin
// Register services.
IocConfiguration.Configure();
// Example controller
public class ExampleController : Controller
{
private readonly ExampleContext _exampleContext;
public ExampleController(ExampleContext exampleContext)
{
_exampleContext = exampleContext;
}
}
Run Code Online (Sandbox Code Playgroud)
要运行迁移:
Add-Migration {MigrationName} -Project Example.EF -StartupProject Example.Tools
Run Code Online (Sandbox Code Playgroud)
我们应该有 IDesignTimeDbContextFactory 来支持运行迁移。
| 归档时间: |
|
| 查看次数: |
1856 次 |
| 最近记录: |