首页 文章

如何使用新的csproj文件修复“没有找到匹配命令的可执行文件”dotnet-ef“”

提问于
浏览
4

我想将SQLite与Entity Framework Core一起使用 . 我正在关注这个官方教程:

.NET Core - New Database

它说要像这样修改project.json:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.EntityFrameworkCore.Sqlite": "1.1.0",
    "Microsoft.EntityFrameworkCore.Design": {
      "version": "1.1.0",
      "type": "build"
    }
  },
  "frameworks": {
    "netcoreapp1.1": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.1.0"
        }
      },
      "imports": "dnxcore50"
    }
  },
  "tools": {
    "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4"
  }
}

我已经安装了VS 2017 RC和Net Core现在使用csproj文件而不是project.json .

我将我的csproj修改为 Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version= "1.1.0-preview4-final" 但是当我尝试命令 dotnet ef migrations add MyFirstMigration 时出现以下错误:

"no executable found matching command "dotnet-ef""

我怎样才能用新的csproj解决这个问题?

1 回答

  • 4

    VS2017将于2017年3月7日正式发布 . 该文件涉及VS2015,它们尚未更新以反映最新的VS 2017变化 . 像这样修改csproject解决了这个问题:

    <ItemGroup>
        <PackageReference Include="Microsoft.Extensions.Configuration" Version="1.1.0" />
        <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="1.1.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.0" />
      </ItemGroup>
    
      <ItemGroup>
      <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version = "1.1.0-preview4-final"/>
      </ItemGroup>
    

    即使在此之后,当我尝试使用CLI命令运行第一次迁移时:

    dotnet ef migrations add MyFirstMigration
    

    我收到以下错误: “No parameterless constructor was found on 'TContext'. Either add a parameterless constructor to 'TContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'TContext'.”

    根据this文档,这是因为设计时工具试图自动查找应用程序如何创建DbContext类型的实例 . 如果EF无法找到初始化DbContext的合适方法,则可能会遇到此错误 .

    我很确定我已经设置了无参数构造函数,并且我能够使用以下CLI命令查看上下文:

    dotnet ef database dbContext list
    

    执行迁移的唯一方法是在项目中实现接口 IDbContextFactory<TContext> . 文档和如何执行此操作的示例基于VS 2015.在VS 2017中 IDbContextFactory<TContext>.Create() 需要 DBContextFactoryOptions 作为参数:

    public class MyContextFactory: IDbContextFactory<MyContext>   
    {
        public MyContext Create(DbContextFactoryOptions options)
        {
            var optionsBuilder = new DbContextOptionsBuilder<MyContext>();       
            optionsBuilder.UseSqlite("Filename=./mydatabase.db");
    
            return new MyContext(optionsBuilder.Options);        
        }
    }
    

相关问题