2017-08-10 54 views
0

我从一台PC移动到一台新的PC,在那里我不得不重新安装每个东西,包括VS2017。但是,当我从旧电脑运行同一个项目到新电脑(两个Windows 10)的应用程序运行良好。然后我添加了一个新的模型,当我运行以下程序包管理器控制台命令时,出现以下错误。ASP.NET添加迁移问题

PM> add-migration myMigration -context TestProjContext 

错误

An error occurred while calling method 'ConfigureServices' on startup class 'Startup'. Consider using IDbContextFactory to override the initialization of the DbContext at design-time. Error: Could not find 'UserSecretsIdAttribute' on assembly 'ef, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. No parameterless constructor was found on 'MyProjContext'. Either add a parameterless constructor to 'MyProjContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'MyProjContext'.

UPDATE

  1. 该项目从VS2015升级到VS2017,因此project.json不见了(换成.csproj如果我还记得。正确地说,这是自从转移到VS2017以来我第一次运行add-migration个命令

Startup.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Hosting; 
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 
using Microsoft.EntityFrameworkCore; 
using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Logging; 
using TestProj.Data; 
using TestProj.Models; 
using TestProj.Services; 

namespace TestProj 
{ 
    public class Startup 
    { 
     public Startup(IHostingEnvironment env) 
     { 
      var builder = new ConfigurationBuilder() 
       .SetBasePath(env.ContentRootPath) 
       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); 

      if (env.IsDevelopment()) 
      { 
       // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 
       builder.AddUserSecrets(); 
      } 

      builder.AddEnvironmentVariables(); 
      Configuration = builder.Build(); 
     } 

     public IConfigurationRoot Configuration { get; } 

     // This method gets called by the runtime. Use this method to add services to the container. 
     public void ConfigureServices(IServiceCollection services) 
     { 
      var connection = @"Server=MyWin10Desktop;Database=MySQL2012Db;Trusted_Connection=True;"; 
      services.AddDbContext<TestProjContext>(options => options.UseSqlServer(connection)); 

      // Add framework services. 
      services.AddDbContext<ApplicationDbContext>(options => 
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

      services.AddIdentity<ApplicationUser, ApplicationRole>() 
       .AddEntityFrameworkStores<ApplicationDbContext>() 
       .AddDefaultTokenProviders(); 

      services.AddMvc(); 
      services.AddDistributedMemoryCache(); 
      services.AddSession(); 

      // Add application services. 
      services.AddTransient<IEmailSender, AuthMessageSender>(); 
      services.AddTransient<ISmsSender, AuthMessageSender>(); 
     } 

     // 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(Configuration.GetSection("Logging")); 
      loggerFactory.AddDebug(); 

      if (env.IsDevelopment()) 
      { 
       app.UseDeveloperExceptionPage(); 
       app.UseDatabaseErrorPage(); 
       app.UseBrowserLink(); 
      } 
      else 
      { 
       app.UseExceptionHandler("/Home/Error"); 
      } 

      app.UseStaticFiles(); 

      app.UseIdentity(); 
      app.UseSession(); //me: must come before app.UseMvc() 

      // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 

      app.UseMvc(routes => 
      { 
       routes.MapRoute(
        name: "default", 
        template: "{controller=Home}/{action=Index}/{id?}"); 
      }); 
     } 
    } 
} 

更新2

TestProj.csproj文件:[注:由于应用程序进行了升级,从VS2015VS2017升级向导删除了project.json并添加了这个.csproj文件,而不是

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

    <PropertyGroup> 
    <TargetFramework>netcoreapp1.1</TargetFramework> 
    <PreserveCompilationContext>true</PreserveCompilationContext> 
    <AssemblyName>ABCTest</AssemblyName> 
    <OutputType>Exe</OutputType> 
    <PackageId>ABCTest</PackageId> 
    <UserSecretsId>aspnet-ABCTest-6af8ade3-87ff-4468-a9ce-8bb69c696ab8</UserSecretsId> 
    <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion> 
    <PackageTargetFallback>$(PackageTargetFallback);dotnet5.6;portable-net45+win8</PackageTargetFallback> 
    </PropertyGroup> 

    <ItemGroup> 
    <None Remove="Properties\PublishProfiles\ABCTestP.pubxml" /> 
    <None Remove="Properties\PublishProfiles\FolderProfile.pubxml" /> 
    <None Remove="Properties\PublishProfiles\FolderProfile1.pubxml" /> 
    </ItemGroup> 

    <ItemGroup> 
    <None Update="wwwroot\**\*;Views\**\*;Areas\**\Views"> 
     <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> 
    </None> 
    </ItemGroup> 

    <ItemGroup> 
    <PackageReference Include="bootstrap" Version="2.3.2" /> 
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.0.0" /> 
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration.Tools" Version="1.1.0-preview4-final" /> 
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0"> 
     <PrivateAssets>All</PrivateAssets> 
    </PackageReference> 
    <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="1.1.1" /> 
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" /> 
    <PackageReference Include="BundlerMinifier.Core" Version="2.3.327" /> 
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" /> 
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="1.1.2" /> 
    <PackageReference Include="EPPlus.Core" Version="1.4.0" /> 
    </ItemGroup> 

<ItemGroup> 
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" /> 
    </ItemGroup> 

</Project> 
+0

你可能达不到这个https://github.com/aspnet/Announcements/issues/209 – Smit

+0

@Smit我想你已经把我在正确的轨道上。我刚刚在上面的UPDATE部分中添加了“item 1”。将我的web项目从VS2015移到VS2017后,错误开始了。由于我再也没有'project.json',我应该关注哪一部分链接 - 你提供了? – nam

+0

你正在使用哪个版本的软件包?分享你的csproj文件。 – Smit

回答

0

相关部分是这样的:

No parameterless constructor was found on MyProjContext . Either add a parameterless constructor to MyProjContext or add an implementation of IDbContextFactory in the same assembly as MyProjContext

IDbContextFactory方法是在实体框架的核心实现这一目标的首选方式,因为你可以使用相同的工具,因为在Startup.cs。 从EF Core documentation

You may also provide an implementation of IDbContextFactory<TContext> . EF tools can use this factory to create an instance of your DbContext. This may be required in order to enable specific design-time experiences such as migrations. Implement this interface to enable design-time services for context types that do not have a public default constructor. Design-time services will automatically discover implementations of this interface that are in the same assembly as the derived context.

例如:

public class DbContextFactory : IDbContextFactory<MyProjContext> 
{ 
    public MyProjContext Create() 
    { 
     var environmentName = Environment.GetEnvironmentVariable("Hosting:Environment"); 
     return Create(Directory.GetCurrentDirectory(), environmentName); 
    } 

    public MyProjContext Create(DbContextFactoryOptions options) 
    { 
     return Create(
      options.ContentRootPath, 
      options.EnvironmentName); 
    } 

    public MyProjContext Create(string basePath, string environmentName) 
    { 
     var builder = new ConfigurationBuilder() 
      .SetBasePath(basePath) 
      .AddJsonFile("appsettings.json") 
      .AddJsonFile($"appsettings.{environmentName}.json", true) 
      .AddEnvironmentVariables(); 

     var Configuration = builder.Build(); 

     var connectionName = nameof(MyProjContext); 
     var connectionString = Configuration.GetConnectionString(connectionName); 
     if (String.IsNullOrWhiteSpace(connectionString) == true) 
      throw new InvalidOperationException($"Could not find a connection string named '{connectionName}'."); 

     // init SQL server 
     var optionsBuilder = new DbContextOptionsBuilder<MyProjContext>(); 
     optionsBuilder.UseSqlServer(connectionString); 

     return new MyProjContext(optionsBuilder.Options); 
    } 
} 
+0

谢谢你试图帮助。我刚刚添加了我的'启动。cs'文件添加到我上面的原始文章中,以便您或某人可以帮助我确切地了解我需要在Startup.cs文件中执行的操作。从我从阅读其他在线文章中收集到的内容,我需要创建您的'DbContextFactory'类。这是模型文件夹下的独立类吗?另外,你的意思是你的类名是'TestProjContextFactory'而不是'DbContextFactory',就像这个[MSDN示例]一样(https://ef.readthedocs.io/en/staging/miscellaneous/configuring-dbcontext.html#use- idbcontextfactory) – nam

+0

我试过你的建议,但得到了我发布的错误[here](https://stackoverflow.com/q/45654180/1232087)。我可能错过了什么? – nam