【问题标题】:NET 5 error when adding migration on Entity Framework Core在 Entity Framework Core 上添加迁移时出现 NET 5 错误
【发布时间】:2021-02-22 20:52:21
【问题描述】:

我正在使用 Entity Framework Core 5 和 Postgres 建立一个新项目。我所有的项目和我的上下文都在同一个项目中。

添加迁移时,我收到此错误:

/src/Api.csproj:错误 MSB4057:项目中不存在目标“GetEFProjectMetadata”。无法检索项目元数据。确保它是基于 MSBuild 的 .NET Core 项目。如果您使用自定义 BaseIntermediateOutputPath 或 MSBuildProjectExtensionsPath 值,请使用 --msbuildprojectextensionspath 选项。

EF Core 版本:5.0.1 目标框架:net5.0

这些是我尝试过的所有命令:

dotnet ef migrations add NewMigration

dotnet ef migrations add NewMigration --msbuildprojectextensionspath     

dotnet ef migrations add NewMigration -p ".\src\Api.csproj"

dotnet ef migrations add NewMigration -p ".\src\Api.csproj" --msbuildprojectextensionspath*     

我尝试了很多我在互联网上找到的选项,但都没有成功。

如果我添加 -v ,最后几行是:

Using project '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj'.
Using startup project '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj'.
Writing '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/obj/Api.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/tmp/tmpbscOwZ.tmp /verbosity:quiet /nologo /media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj
/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj : error MSB4057: O destino "GetEFProjectMetadata" não existe no projeto.
Microsoft.EntityFrameworkCore.Tools.CommandException: Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
   at Microsoft.EntityFrameworkCore.Tools.Project.FromFile(String file, String buildExtensionsDir, String framework, String configuration, String runtime)
   at Microsoft.EntityFrameworkCore.Tools.RootCommand.Execute(String[] _)
   at Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.<Configure>b__0(String[] args)
   at Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[] args)
   at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.

Api.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <DocumentationFile>bin\Debug\net5.0\comments.xml</DocumentationFile>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <noWarn>1591;1572;1573</noWarn>
    <PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
    <CodeAnalysisRuleSet>../roslynator.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  
  <ItemGroup>
    <PackageReference Include="FluentValidation" Version="9.4.0" />
    <PackageReference Include="FluentValidation.AspNetCore" Version="9.4.0" />
    <PackageReference Include="Mapster" Version="7.0.1" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
    <PackageReference Include="Scrutor" Version="3.3.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.1" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.1" />
    <PackageReference Include="jaeger" Version="0.4.2" />
    <PackageReference Include="OpenTracing.Contrib.NetCore" Version="0.7.1" />
    <PackageReference Include="RestSharp" Version="106.2.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.1" />
    <PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.1" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
    <PackageReference Include="Microsoft.OpenApi" Version="1.2.3" />
    <PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="5.6.3" />
  </ItemGroup>

  <ItemGroup>
    <None Include="*.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="Always" />
    <None Include="Locales\**\*.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="Always" />
  </ItemGroup>
</Project>

程序.cs:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace Linear.Service_Name.Api
{
  public static class Program
  {
    public static void Main(string[] args)
    {
      CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
      WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
  }
}

Startup.cs:

using Linear.Service_Name.DataBase.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

[assembly: Microsoft.AspNetCore.Mvc.ApiController]
namespace Linear.Service_Name.Api
{
  public class Startup
  {
    private IWebHostEnvironment _environment { get; }

    public Startup(IConfiguration _, IWebHostEnvironment environment)
    {
      _environment = environment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddDbContext<Context>(opt => opt
        .UseNpgsql(EnvVariables.LINEAR_API_DOMAIN_NAME_DB_CONNECTION_STRING)
      );
      services.AddCommonsServices<Context>(new CommonServices
      {
        Env = _environment,
        ConnectionString = EnvVariables.LINEAR_API_DOMAIN_NAME_DB_CONNECTION_STRING,
        Assembly = Assembly.GetExecutingAssembly(),
        Swagger = new CommonServices.SwaggerSettings{
          Version = "v1",
          Title = "Service_Name",
          Description = "API REST do Módulo de " + ("Service_Name").ToUpper()
            + " da solução SG Web."
        }
      });
    }

    public void Configure(IApplicationBuilder app)
    {
      app.UserCommonsMiddlewares(new CommonMiddlewares
      {
        Env = _environment,
        PathBase = EnvVariables.LINEAR_API_SERVICE_NAME_BASE_PATH,
        Swagger = new CommonMiddlewares.SwaggerSettings
        {
          Version = "v1",
          Title = "Service_Name"
        }
      });
    }
  }
}

Context.cs:

using Linear.Infrastructure.Data.Audit;
using Linear.Infrastructure.Data.MultiTenancy;
using Microsoft.EntityFrameworkCore;

namespace Linear.Service_Name.DataBase.Entities
{
  public class Context : DbContext
  {
    public virtual DbSet<Sample_NamesEntity> Sample_Names { get; set; }
    private readonly IAuditEntity _auditEntity;
    private readonly IMultiTenancy _multiTenancy;
    public Context(DbContextOptions<Context> options, IAuditEntity auditEntity,
      IMultiTenancy multiTenancy)
      : base(options)
    {
      _auditEntity = auditEntity;
      _multiTenancy = multiTenancy;
    }
    #region Métodos Protegidos
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
      => modelBuilder.ApplyConfigurationsFromAssembly(typeof(Context).Assembly);

    #endregion
    #region Métodos Públicos
    public override int SaveChanges()
    {
      _multiTenancy.OnSaveChanges(this);
      _auditEntity.OnSaveChanges(this);
      return base.SaveChanges();
    }
    public int SaveChangesWithoutMultiTenancy()
    {
      _auditEntity.OnSaveChanges(this);
      return base.SaveChanges();
    }
    public int SaveChangesWithoutMultiTenancyAndAudit() => base.SaveChanges();
    #endregion
  }
}

项目下载链接: https://drive.google.com/file/d/1YWlm_teyGMjJe193AwrFqe3VAeVVKWLq/view?usp=sharing

我被这个问题困扰了3个多小时,在网上尝试了很多建议,仍然没有成功,如果我能得到一些帮助,我将不胜感激。

【问题讨论】:

    标签: c# .net docker entity-framework entity-framework-core


    【解决方案1】:

    经过一番研究,似乎与 docker 集成和 EF Core 工具的项目存在问题。

    我已经下载了你的代码,这是你Directory.Build.props的内容

    <Project>
      <PropertyGroup>
        <DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)/obj/**/*</DefaultItemExcludes>
        <DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)/bin/**/*</DefaultItemExcludes>
      </PropertyGroup>
    
      <PropertyGroup Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' == 'true'">
        <BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/obj/container/</BaseIntermediateOutputPath>
        <BaseOutputPath>$(MSBuildProjectDirectory)/bin/container/</BaseOutputPath>
      </PropertyGroup>
    
      <PropertyGroup Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' != 'true'">
        <BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/obj/local/</BaseIntermediateOutputPath>
        <BaseOutputPath>$(MSBuildProjectDirectory)/bin/local/</BaseOutputPath>
      </PropertyGroup>
    
    </Project>
    

    根据this issue中的@bricelam,问题的根源在这里:

    BaseIntermediateOutputPath不在一个 容器打破 EF Core 工具体验(*)

    由于在 docker 容器外运行时,您的 BaseIntermediateOutputPath 从其默认值更改为 obj/local,因此您需要做的是让 EF Core CLI 知道在哪里可以找到该文件夹​​。您可以通过使用--msbuildprojectextensionspath 参数来完成此操作。在您的情况下,它会像这样 (as suggested here):

    dotnet ef migrations add NewMigration --msbuildprojectextensionspath obj/local
    

    如果您仍然无法使其工作,您可以关注in this other issue 的讨论。在那里,有人建议another possible fix 更改您的Directory.Build.props*.csproj 文件,使后者看起来如下所示:

    <Project> <!-- Note: No Sdk="" here. -->
    
      <PropertyGroup>
         <!-- Don't use $(Configuration) since it isn't set yet. -->
        <MSBuildProjectExtensionsPath>$(MSBuildProjectDirectory)\_intermediate_\</MSBuildProjectExtensionsPath>
      </PropertyGroup>
    
      <!-- MSBuildProjectExtensionsPath must be set before this gets imported. Directory.Build.props is too late. -->
      <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
    
      <!-- (Project content goes here) -->
    
      <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
    
    </Project>
    

    【讨论】:

    • 哇,非常感谢您的努力和帮助。最后添加 --msbuildprojectextensionspath obj/local 解决了我的问题。
    • @PabloChristian 不客气,很高兴它有帮助 ?
    • 好电话,我在 bin 和 obj 目录中添加了 .,因为它们妨碍了 vscode,这就是第一次失败的原因。
    猜你喜欢
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2019-01-11
    • 2017-06-17
    • 1970-01-01
    相关资源
    最近更新 更多