EF核心迁移失败

时间:2020-05-20 23:12:28

标签: c# entity-framework-core

我是使用EF Core构建Code First的新手,需要一点帮助。我有3个项目的解决方案:DataProvider,DataModel,UserInterface。我大致遵循乔恩·史密斯(Jon P Smith)的《实体框架在行动》一书中的示例。

DataModel保存我的ef实体(类定义)。 DataProvider持有我的DbContext。 UserInterface是启动Web应用程序。

我在DataProvider> P1DbContext.cs中具有以下内容:

namespace DataProvider
{
    public class P1DbContext : DbContext
    {

        public DbSet<ToDoItem> ToDoItems { get; set; }

        public P1DbContext(DbContextOptions<P1DbContext> options) : base(options) { }

    }
}

以及DataProvider> ContextFactoryForMigrations.cs中的以下内容(Jon P Smith建议在一个解决方案中进行多个项目的迁移):

class ContextFactoryForMigrations : IDesignTimeDbContextFactory<P1DbContext>
{

    private const string ConnectionString = "Server=localhost;Database=master;Trusted_Connection=True;";

    public P1DbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<P1DbContext>();
        optionsBuilder.UseSqlServer(ConnectionString,
            b => b.MigrationsAssembly("DataProvider"));

        return new P1DbContext(optionsBuilder.Options);
    }

}

然后在UserInterface> Startup.cs中找到它:

public void ConfigureServices(IServiceCollection services)
        {
            string connection = "Server = localhost; Database = master; Trusted_Connection = True;";
            services.AddMvc();
            services.AddDbContext<P1DbContext>(options => options.UseSqlServer(connection,
                b => b.MigrationsAssembly("DataProvider")));
        }

进行正确的引用,并编译所有项目。

当我进入Package Manager控制台时,我运行以下命令,其中DataProvider作为PM Console中的默认项目,而UserInterface作为解决方案中的启动项目:

Add-Migration InitializeDb -Project DataProvider -StartupProject UserInterface

我收到此回复:

Could not load assembly ''. Ensure it is referenced by the startup project ''.

它甚至都不知道要寻找哪个程序集或启动项目是什么。我确定我在这里错过了一些愚蠢的事情,但我想我要问一下,然后再把头撞墙的时间再长一点。

这里是到项目的当前状态的回购链接:https://github.com/philipwalter/CodeFirstEFTest

如果有人可以帮助我克服最初的“代码优先”驼峰,剩下的事情我都可以解决。

1 个答案:

答案 0 :(得分:1)

我的问题已由杰里米·莱克曼(Jeremy Lakeman)在上述评论中正确诊断。使用NuGet,我将EntityFrameworkCore.Tools和EntityFrameworkCore.SqlServer 3.x引入了.NET Core 2.x项目。我删除了这些引用并添加了EF版本以匹配我的.NET Core版本,并且Add-Migration命令成功运行。感谢Jeremy和ESG的帮助!