在Visual Studio 2017中将EF Core创建为单独的项目 [英] Create EF Core as separate project in Visual Studio 2017

查看:82
本文介绍了在Visual Studio 2017中将EF Core创建为单独的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个单独的EF Core 2作为单独的项目.

I'm trying to create a separate EF Core 2 as separate project.

我创建了一个类库(.net核心),添加了两个引用: Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Design

I created a class library (.net core), add two references: Microsoft.EntityFrameworkCore, Microsoft.EntityFrameworkCore.Design

然后我遇到了类似的错误:

Then I met an error like:

未找到指定的框架'Microsoft.NETCore.App',版本'2.0'

The specified framework 'Microsoft.NETCore.App', version '2.0' was not found

我通过在根文件夹中添加一个名为 global.json 的json文件来解决,该文件的内容为:

I solved by adding in root folder a json file called global.json which content is:

{
   "sdk": {
      "version": "2.0.2"
   }
}

很好,直到这里.

如果我运行命令: dotnet ef更新数据库,它将告诉您:

If I run command: dotnet ef update database it tells that:

尚未为此DbContext配置数据库提供程序.

No database provider has been configured for this DbContext.

大多数人说我必须在 Startup.cs 中注册.但是我没有它,因为该项目是类库,没有mvc核心应用程序.

Most of people said that I have to register in Startup.cs. But I don't have it because the project is class library, no mvc core application.

那么,在这种情况下该怎么做?

So, what steps to do in this case ?

当然,我有一个单独的mvc核心项目,该项目引用了该EF核心项目.我应该在该 Startup.cs 文件中注册dbcontext吗?

Of course, I have a separate project for mvc core which has reference to that EF core project. Should I register the dbcontext in that Startup.cs file ?

推荐答案

假设自从我这样做以来的最近几周内没有任何变化:

Assuming nothing had changed in the last few weeks since I did this:

创建类 DesignTimeDbContextFactory (用您的 DbContext 的名称替换 ApplicationDbContext :

Create class DesignTimeDbContextFactory (replacing ApplicationDbContext with the name of your DbContext:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var connectionString = "Server=(localdb)\\mssqllocaldb;Database=MyDbName;Trusted_Connection=True;MultipleActiveResultSets=true";

        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();

        builder.UseSqlServer(connectionString);

        return new ApplicationDbContext(builder.Options);
    }
}

现在执行以下操作之一:

Now do one of the following:

  • 如果使用添加迁移"和更新数据库"命令行开关,请使用-project [项目名称]标志

  • if using the Add-Migration and Update-Database commandlets use the -project [project-name] flag

如果从命令行使用dotnet,请使用--project [project-name]标志

if using dotnet from command line use the --project [project-name] flag

,或者您可以确保将此类库设置为启动项目,并在PM控制台中将其设置为默认项目",然后添加迁移并更新数据库

or you can ensure that this class library is set as startup project and also set in the PM console the 'Default Project' and then add your migrations and update the database

这篇关于在Visual Studio 2017中将EF Core创建为单独的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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