[英]Error -The Entity Framework package is not installed on project when I try to enable migration in .net core 2.2
[英]NET 5 error when adding migration on Entity Framework Core
我正在使用 Entity Framework Core 5 和 Postgres 建立一個新項目。 我所有的項目和我的上下文都在同一個項目中。
添加遷移時,我收到此錯誤:
/src/Api.csproj:錯誤 MSB4057:項目中不存在目標“GetEFProjectMetadata”。 無法檢索項目元數據。 確保它是基於 MSBuild 的 .NET 核心項目。 如果您使用自定義 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>();
}
}
啟動.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 in this issue ,問題的根源在於:
不在容器內運行時將
BaseIntermediateOutputPath
更改為默認值會破壞 EF Core 工具體驗(*)
由於在 docker 容器外運行時,您的BaseIntermediateOutputPath
從其默認值更改為obj/local
,因此您需要做的是讓 EF Core CLI 知道在哪里可以找到該文件夾。 您可以通過使用--msbuildprojectextensionspath
參數來完成此操作。 在您的情況下,它會像這樣( 如建議here ):
dotnet ef migrations add NewMigration --msbuildprojectextensionspath obj/local
如果您仍然無法使其工作,您可以關注this other issue中的討論。 在那里,有人建議另一個可能的解決方法是稍微更改一下您的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.