添加迁移ef core 2预览1时出错 [英] Error while Add-Migration ef core 2 preview 1

查看:78
本文介绍了添加迁移ef core 2预览1时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ef core 2上做一个示例,但是当我尝试添加迁移时得到了以下提示

I'm trying to do a sample on ef core 2 but I'm getting the following when I try to add migrations

PM> Add-Migration InitialCreate
No parameterless constructor was found on 'ToDoContext'. Either add a parameterless constructor to 'ToDoContext' or add an implementation of 'IDbContextFactory<ToDoContext>' in the same assembly as 'ToDoContext'.

我遵循了本教程> https://docs.microsoft.com/zh-cn/ef/core/get-started/aspnetcore/new-db 这是我的代码。

I followed this tutorial https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db Here is my code.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;";
        services.AddDbContext<ToDoContext>(options => options.UseSqlServer(connection));
        services.AddMvc();
    }
}

public class ToDoContext : DbContext
{
    public ToDoContext(DbContextOptions<ToDoContext> options)
        : base(options)
    {

    }
    public DbSet<ToDo> ToDos { get; set; }
}

public class ToDo
{
    public int Id { get; set; }
    public string Title { get; set; }
    public bool Completed { get; set; }
}


推荐答案

我建议实施 IDbContextFactory 。这是一个示例。

I recommend implementing IDbContextFactory. Here is an example.

class ToDoContextFactory : IDbContextFactory<ToDoContext>
{
    public ToDoContext Create(DbContextFactoryOptions options)
    {
        var serviceCollection = new ServiceCollection()
            .AddLogging();
        new Startup().ConfigureServices(serviceCollection);

        var serviceProvider = serviceCollection.BuildServiceProvider();

        return serviceProvider.GetRequiredService<ToDoContext>();
    }
}

在2.0版中,ASP.NET Core团队更新了推荐的用于构建应用程序的模式。这打破了EF Core工具访问应用程序服务提供商的方式。这导致我们删除了调用 Startup.ConfigureService 的方式,并将其更新为改为调用 Program.BuildWebHost 。这意味着从1.x升级到2.0的所有应用程序都将需要更新为新模式或实施 IDbContextFactory 才能使用2.0工具。

In 2.0, the ASP.NET Core team updated the recommended pattern for building apps. This broke the way the EF Core tools accessed the application's service provider. This lead us to remove the way we invoked Startup.ConfigureService and update it to invoke Program.BuildWebHost instead. This means that any apps upgrading from 1.x to 2.0 will either need to update to the new pattern or implement IDbContextFactory before they can use the 2.0 tools.

这篇关于添加迁移ef core 2预览1时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆