我從一台PC轉移到一台新PC上,我不得不重新安裝包括VS2017在內的所有東西。但是,當我從舊PC運行我的同一個項目到新的PC(兩個Windows 10)應用程序運行正常。然後我添加了一個新模型,當我運行以下Package Manager控制台命令時,我收到以下錯誤。

PM> add-migration myMigration -context TestProjContext

錯誤

在啟動類'Startup'上調用方法'ConfigureServices'時發生錯誤。考慮使用IDbContextFactory在設計時覆蓋DbContext的初始化。錯誤:無法在程序集'ef,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = adb9793829ddae60'上找到'UserSecretsIdAttribute'。在'MyProjContext'上找不到無參數構造函數。要么將無參數構造函數添加到'MyProjContext',要么在與'MyProjContext'相同的程序集中添加'IDbContextFactory'的實現。

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文件 :[注意:自從應用程序從VS2015升級到VS2017 ,升級嚮導刪除了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>

熱門答案

相關部分是這樣的:

MyProjContextMyProjContext無參數構造MyProjContext 。向MyProjContext添加無參數構造MyProjContext或在與IDbContextFactory相同的程序MyProjContext添加MyProjContext的實現

IDbContextFactory方式是在Entity Framework Core中實現此目的的首選方法,因為您可以使用與Startup.cs相同的工具。從EF Core文檔

您還可以提供IDbContextFactory<TContext> 。 EF工具可以使用此工廠來創建DbContext的實例。 這可能是必需的,以便實現特定的設計時體驗,例如遷移 。實現此接口以為沒有公共默認構造函數的上下文類型啟用設計時服務。設計時服務將自動發現此接口的實現,這些實現與派生上下文在同一程序集中。

例如:

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);
    }
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow