c# - NET 5 在 Entity Framework Core 上添加迁移时出错

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

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

添加迁移时,出现此错误:

/src/Api.csproj : error MSB4057: The target "GetEFProjectMetadata" does not exist in the project. Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.

EF 核心版本: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>();
  }
}

启动.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"
        }
      });
    }
  }
}

上下文.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 个多小时,在网上尝试了很多建议,但仍然没有成功,如果我能得到一些帮助,我将不胜感激。

最佳答案

经过一些研究,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>

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

Changing BaseIntermediateOutputPath from its default when not running inside a container breaks the EF Core tooling experience (*)

由于在 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>

关于c# - NET 5 在 Entity Framework Core 上添加迁移时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66323260/

相关文章:

c# - 无法将 CSS 应用于 html 字符串

c# - 扑克 watch 示和评估

c# - .net 4 部分信任来自 GAC 的程序集

docker - Logstash Kafka输入无法连接

java - Docker 构建在下载期间挂起

c# - RDLC 表 - 垂直和水平合并单元格

c# - Func 或 Predicate 到 ExpressionTree

c# - 等待几秒钟而不阻止 UI 执行

.net - 通过 Visual Studio 2022 使用 C# 10 隐式使用发布 .NET 6 项目

php - Xdebug Netbeans Php Docker