Entity Framework Core和Entity Framework 6都已安装。

27

我使用Visual Studio 2017创建了一个新的ASP.NET Core项目。如下所示,我为Entity Framework Core添加了迁移。

add-migration "Initial Create"

并且收到以下错误:

Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework\Add-Migration' for Entity Framework 6.
Build Failed.

你知道如何解决这个错误吗?


更新1 - 2017年3月14日 - 运行命令后收到的结果

PM> dotnet ef migrations add "Initial Create"

我看到以下输出,末尾带有错误信息。

Welcome to .NET Core!
---------------------
Learn more about .NET Core @ https://aka.ms/dotnet-docs. Use dotnet --help to see available commands or go to https://aka.ms/dotnet-cli-docs.

Telemetry
--------------
The .NET Core tools collect usage data in order to improve your experience. The data is anonymous and does not include command-line arguments. The
 data is collected by Microsoft and shared with the community.
You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell.
You can read more about .NET Core tools telemetry @ https://aka.ms/dotnet-cli-telemetry.

Configuring...
-------------------
A command is running to initially populate your local package cache, to improve restore speed and enable offline access. This command will take up
 to a minute to complete and will only happen once.
Decompressing 0%Decompressing 1%Decompressing 2%Decompressing 3%Decompressing 4%
Decompressing 5%Decompressing 6%Decompressing 7%Decompressing 8%Deco
mpressing 9%Decompressing 10%Decompressing 11%Decompressing 12%Decompressing 13
%Decompressing 14%Decompressing 15%Decompressing 16%Decompressing 17%
Decompressing 18%Decompressing 19%Decompressing 20%Decompressing 21%De
compressing 22%Decompressing 23%Decompressing 24%Decompressing 25%Decompressin
g 26%Decompressing 27%Decompressing 28%Decompressing 29%Decompressing 30%
Decompressing 31%Decompressing 32%Decompressing 33%Decompressing 34%
Decompressing 35%Decompressing 36%Decompressing 37%Decompressing 38%Decompre
ssing 39%Decompressing 40%Decompressing 41%Decompressing 42%Decompressing 43%
Decompressing 44%Decompressing 45%Decompressing 46%Decompressing 47%
Decompressing 48%Decompressing 49%Decompressing 50%Decompressing 51%Deco
mpressing 52%Decompressing 53%Decompressing 54%Decompressing 55%Decompressing 
56%Decompressing 57%Decompressing 58%Decompressing 59%Decompressing 60%
Decompressing 61%Decompressing 62%Decompressing 63%Decompressing 64%
Decompressing 65%Decompressing 66%Decompressing 67%Decompressing 68%Decompress
ing 69%Decompressing 70%Decompressing 71%Decompressing 72%Decompressing 73%
Decompressing 74%Decompressing 75%Decompressing 76%Decompressing 77%
Decompressing 78%Decompressing 79%Decompressing 80%Decompressing 81%Decomp
ressing 82%Decompressing 83%Decompressing 84%Decompressing 85%Decompressing 86
%Decompressing 87%Decompressing 88%Decompressing 89%Decompressing 90%
Decompressing 91%Decompressing 92%Decompressing 93%Decompressing 94%De
compressing 95%Decompressing 96%Decompressing 97%Decompressing 98%Decompressin
g 99%Decompressing 100% 5083 ms
Expanding 0%Expanding 1%Expanding 2%Expanding 3%Expanding 4%Expanding 5%Ex
panding 6%Expanding 7%Expanding 8%Expanding 9%Expanding 10%Expanding 11%
Expanding 12%Expanding 13%Expanding 14%Expanding 15%Expanding 16%Expanding 17%
Expanding 18%Expanding 19%Expanding 20%Expanding 21%Expanding 22%Expand
ing 23%Expanding 24%Expanding 25%Expanding 26%Expanding 27%Expanding 28%
Expanding 29%Expanding 30%Expanding 31%Expanding 32%Expanding 33%Expanding 34
%Expanding 35%Expanding 36%Expanding 37%Expanding 38%Expanding 39%Ex
panding 40%Expanding 41%Expanding 42%Expanding 43%Expanding 44%Expanding 45%
Expanding 46%Expanding 47%Expanding 48%Expanding 49%Expanding 50%Expandin
g 51%Expanding 52%Expanding 53%Expanding 54%Expanding 55%Expanding 56%
Expanding 57%Expanding 58%Expanding 59%Expanding 60%Expanding 61%Expanding 62%
Expanding 63%Expanding 64%Expanding 65%Expanding 66%Expanding 67%Expa
nding 68%Expanding 69%Expanding 70%Expanding 71%Expanding 72%Expanding 73%
Expanding 74%Expanding 75%Expanding 76%Expanding 77%Expanding 78%Expanding 
79%Expanding 80%Expanding 81%Expanding 82%Expanding 83%Expanding 84%
Expanding 85%Expanding 86%Expanding 87%Expanding 88%Expanding 89%Expanding 90%
Expanding 91%Expanding 92%Expanding 93%Expanding 94%Expanding 95%Expand
ing 96%Expanding 97%Expanding 98%Expanding 99%Expanding 100% 13884 ms


dotnet : No executable found matching command "dotnet-ef"
At line:1 char:1
+ dotnet ef migrations add "Initial Create"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (No executable f...and "dotnet-ef":String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

更新 2 - 2017年3月14日 - Startup.cs文件

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using OdeToFood.Services;
using OdeToFood.Entities;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace OdeToFood
{
    public class Startup
    {
        public IConfiguration Configuration { get; set; }

        public Startup(IHostingEnvironment env)
        {
            // TN - Read setting files
            var builder = new ConfigurationBuilder()
                            .SetBasePath(env.ContentRootPath)
                            .AddJsonFile("appsettings.json")
                            .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton(Configuration);
            services.AddSingleton<IGreeter, Greeter>();
            services.AddScoped<IRestaurantData, SqlRestaurantData>(); // TN - One instance of this service for each HTTP request.
            services.AddDbContext<OdeToFoodDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity<User, IdentityRole>()
                .AddEntityFrameworkStores<OdeToFoodDbContext>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //app.UseExceptionHandler("/error");
                //app.UseExceptionHandler(new ExceptionHandlerOptions { ExceptionHandlingPath="/error" });

                app.UseExceptionHandler(new ExceptionHandlerOptions
                {
                    ExceptionHandler = context => context.Response.WriteAsync("Opps!")
                });
            }

            //app.UseDefaultFiles();// TN - will pick index.html
            //app.UseStaticFiles();

            app.UseFileServer(); // TN - This will include UseDefaultFiles() and UseStaticFiles

            /*
            app.UseWelcomePage(new WelcomePageOptions
            {
                Path = "/welcome"
            });

            app.Run(async (context) =>
            {
                // TN - Read directly from configuration file
                //var message = Configuration["Greeting"];

                // TN - Dependency Injection - Read from configuration string via IOC
                var message = greeter.GetGreeting();
                await context.Response.WriteAsync(message);
            });
            */


            app.UseIdentity();

            //app.UseMvcWithDefaultRoute();
            app.UseMvc(ConfigureRoutes);

            // TN - if no route matches
            app.Run(ctx => ctx.Response.WriteAsync("Not found."));
        }

        private void ConfigureRoutes(IRouteBuilder routeBuilder)
        {
            //Home/Index
            routeBuilder.MapRoute("Default",
                "{controller=Home}/{action=Index}/{id?}");
        }
    }
}

更新3 - 2017年3月14日 - 添加了csproj文件

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

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PackageTargetFallback>portable-net45+win8</PackageTargetFallback>
  </PropertyGroup>

  <ItemGroup>
    <!--<Content Include="wwwroot\index.html" />-->
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Controllers\" />
    <Folder Include="Data\" />
    <Folder Include="Views\Home\" />
    <Folder Include="wwwroot\images\" />
  </ItemGroup>

</Project>

你发布的第一个错误(关于EF6已安装)并不是错误,只是一个警告。EFCore迁移应该能够成功从那个命令添加。除了警告之外,你还遇到了其他问题吗? - Smit
1
我在那个警告之后收到了一个“构建失败”的消息。 - Tuyen Nguyen
1
当EF Core执行任何命令时,首先会构建项目。错误消息指示无法构建项目。尝试在Visual Studio中构建项目,并查看错误列表窗口以查看构建错误。此故障与特定的EF无关。 - Smit
7个回答

45

如何在VS 2017|2019中解决这个问题

  • 从解决方案的所有项目中删除EntityFramework (不是EntityFrameworkCore)的引用
  • 在资源管理器(Windows资源管理器)中打开解决方案文件夹
  • 关闭VS
  • 删除.vs文件夹
  • 重新打开解决方案
  • 运行update-database,警告就会消失

你看不到'.vs'文件夹吗?

enter image description here


删除.vs文件夹是必须的。也许我曾经测试过添加一些非核心包,但我已经将它们移除了。然后,由于看不到这些包,我以为一切都没问题。但实际上并非如此。删除.vs文件夹解决了这个问题! - Master DJon

13
对于那些使用新版 Entity Framework 6.3及更高版本到.Net Core 的用户来说,很可能解决方案将包括EfCore和Ef6工件。
例如,我已经将旧的EF6存储库从.Net Framework迁移到了Core,但想要利用开箱即用的AspNet Identity Core子系统,该子系统使用EfCore。
在迁移过程中,我总是会随意收到错误提示,比如:
“同时安装了Entity Framework Core和Entity Framework 6。正在运行Entity Framework Core工具。请使用'EntityFramework6\Update-Database'进行Entity Framework 6。”
或者
“同时安装了Entity Framework 6和Entity Framework Core。正在运行Entity Framework 6工具。请使用'EntityFrameworkCore\Add-Migration'进行Entity Framework Core。”
解决方法很简单 - 按照警告,在运行迁移命令时始终使用完全限定的命令:
EntityFramework6\Add-Migration Foo
EntityFramework6\Update-Database

或者

EntityFrameworkCore\Add-Migration Foo
EntityFrameworkCore\Update-Database

请注意,对于EF6的粉丝,在撰写本文时,迁移工具转移到Core还不够完善,详情请参见此处
同样地,如果您在同一框架版本中有多个DbContext(EfCore vs Ef6 on Core),您需要指定要针对的特定DbContext的名称,例如:
EntityFramework6\Add-Migration Foo -Context BarDbContext
EntityFramework6\Add-Migration Baz -Context FooDbContext

1
我相信你是正确的,尽管在我的情况下,如果我没有使用EF6/EF Core限定命令,Visual Studio会给我一个关于“-Context”参数不存在的神秘错误,而只有在我使用限定命令时才会显示突出的警告,这让我感到困惑。 - intcreator
如果使用EntityFramework6\Add-Migration命令,我们需要添加旧参数 EntityFramework6\Add-Migration -Force -ProjectName -StartUpProjectName -ConfigurationTypeName -ConnectionStringName -IgnoreChanges -AppDomainBaseDirectory。 - amc software

8

也许你的解决方案中至少有两个项目,每个项目都使用EF的不同版本。通过发出“管理解决方案的NuGet包...”命令,您可以验证这一点。然后,也许您需要放弃使用EF 6.x的那个项目。之后您需要重新启动VS,因为某些缓存可能会在卸载时阻止完全删除该软件包。

编辑:...或者您可以很好地同时使用它们,但要仔细阅读消息并按照其指示操作...


4
这对我来说就足够了。在我的情况下,诀窍是在从我的解决方案中删除EF6后没有重新启动Visual Studio。即使不再有项目使用EF6,只使用EFCore,我仍然收到这个消息。重新启动Visual Studio后,它就消失了。 - jozolo
我也遇到了同样的问题。重启 VS 解决了它。 - James
@Alexander_Christov 请详细阐述您的答案。这个回答不是很清晰。 - Manish Jain

4
如果已经安装了Entity Framework Core和Entity Framework 6,并且您想要使用Entity Framework 6。
请在Package Manager Console中使用以下命令:
'EntityFramework\Update-Database'.

无需删除或更改任何内容,只需在EF6命令之前添加**EntityFramework**即可。


1
截至2023年1月,EF6不再得到开发,因此建议新项目使用EF Core。来源 - intcreator

2

为EF7添加迁移,使用dotnet命令:dotnet ef migrations add Initial
要更新数据库,请使用dotnet命令:dotnet ef database update


你是否尝试从类库中添加迁移? - agua from mars
你能发布你的 Startup.cs 文件吗? - agua from mars
请问您在 csproj 文件中是否找到了 <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />? - agua from mars
我已经在我的问题中添加了Startup.cs。我已经在我的csproj中添加了你的设置,但它仍然失败。我在我的项目中使用Entity Framework Core,所以我不确定EF 7命令是否会解决这个问题。我意识到我已经将这个ASP.NET Core Web应用程序添加到一个现有解决方案中,该解决方案已经有几个ASP.NET MVC 4应用程序,这使得包管理器控制台感到困惑。我创建了一个全新的解决方案,并向其中添加了一个新的ASP.NET Core Web应用程序,我可以成功运行**add-migration "Initial Create"**。 - Tuyen Nguyen
你是如何在你的csproj中添加EF 7工具的?dotnet命令应该可以工作。 - agua from mars
显示剩余3条评论

1
我现在就像这样修复了:
  1. 打开:Visual Studio > 包管理器控制台
  2. 运行此命令:Remove-Module EntityFramework6

1

只需要...

编辑你的项目 (项目 -> 右键 -> 编辑),并删除 EntityFramework 相关行

删除类似于以下这一行:

    <PackageReference Include="Entityframework" Version="6.2.0" />

并且仅使用EntityFramework Core


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接