简体   繁体   English

实体框架核心 - 迁移 - 没有为此对象定义无参数构造函数

[英]Entity Framework Core - Migration - No Parameterless Constructor Defined for this Object

I am working with the latest .Net Core and EF Core in Visual Studio 2017. I have created a model and it was working great.我正在 Visual Studio 2017 中使用最新的 .Net Core 和 EF Core。我已经创建了一个模型并且它运行良好。 I have since made some modifications and am getting the following error when I try to add a new migration:此后,我进行了一些修改,但在尝试添加新迁移时出现以下错误:

Build succeeded.
  0 Warning(s)
  0 Error(s)

Time Elapsed 00:00:09.08
System.MissingMethodException: No parameterless constructor defined for this object.
  at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
  at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
  at System.Activator.CreateInstance(Type type, Boolean nonPublic)
  at System.Activator.CreateInstance(Type type)
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_0.<FindContextTypes>b__3()
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
  at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No parameterless constructor defined for this object.

I have compared my code since the last check in and have commented out certain chunks of code to see if the error persists and whatever I comment out, it still fails with the same error.自上次签入以来,我已经比较了我的代码,并注释掉了某些代码块,以查看错误是否仍然存在,无论我注释掉什么,它仍然会因相同的错误而失败。

Question: Is there a way to get more detailed information on exactly WHAT type does not have a parameterless constructor?问题:有没有办法获得关于 WHAT 类型没有无参数构造函数的更详细信息? Or even run this from within VS and perhaps get a breakpoint?或者甚至从 VS 中运行它并可能获得断点?

Update: Based on some of the comments, here is some code.更新:根据一些评论,这里有一些代码。

For the DbContext override对于DbContext覆盖

public class AlmanacDb : IdentityDbContext<ApplicationUser, ApplicationRole, int> {

  private readonly ILogger logger;

  public AlmanacDb(DbContextOptions<AlmanacDb> options, ILoggerFactory loggerFactory) : base(options) {
    this.logger = loggerFactory.CreateLogger<AlmanacDb>();
  }

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
    optionsBuilder.UseSqlServer("Server=.\\SQLExpress;Database=Almanac;Trusted_Connection=True;MultipleActiveResultSets=True;");
  }

  ...
}

I do have a IDbContextFactory but it is not referenced anywhere and worked without a reference.我确实有一个IDbContextFactory但它没有在任何地方被引用,并且在没有引用的情况下工作。 Not sure if this is a problem or not based on a link provided in the 2nd comment.根据第二条评论中提供的链接,不确定这是否是问题。 If memory serves, as long as the IDbContextFactory is within the solution, it should find it?如果没记错的话,只要IDbContextFactory在解决方案内,应该能找到吧?

public class AlmanacDbFactory : IDbContextFactory<AlmanacDb> {

  private IConfigurationRoot configuration;
  private readonly ILoggerFactory loggerFactory;

  public AlmanacDbFactory(ILoggerFactory loggerFactory) {
    var builder = new ConfigurationBuilder()
     .SetBasePath(System.AppContext.BaseDirectory)
     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

    this.configuration = builder.Build();
    this.loggerFactory = loggerFactory;
  }

  public AlmanacDb Create(DbContextFactoryOptions options) {
    var optionsBuilder = new DbContextOptionsBuilder<AlmanacDb>();
    optionsBuilder.UseSqlServer(
      configuration.GetConnectionString("AlmanacSQL"), m => { m.EnableRetryOnFailure(); }
    );

    return new AlmanacDb(optionsBuilder.Options, loggerFactory);
  }
}

My Startup.cs class我的Startup.cs

public void ConfigureServices(IServiceCollection services) {
  try {
    services.AddDbContext<AlmanacDb>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("AlmanacSQL"))
    );
    services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

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

    services.AddScoped<SignInManager<ApplicationUser>, AvantiaSignInManager<ApplicationUser>>();

    services.AddAuthorization(x => {
      x.AddPolicy("EmployeeOnly", p => p.RequireClaim("EmployeeNumber"));
    });

    services.AddMvc();
  } catch (Exception e) {
    Console.WriteLine(e.ToString());
    throw;
  }
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, AlmanacDb context) {
  ... // Nothing actually touches the AlmanacDb within this code so I left it out
}

Update 2: Solutiuon Seeing that I am learning ASP.Net Core I am reading a ton of sites (including docs.microsoft.com) at one point I put in the IDbContextFactory code as you can see above.更新 2:解决方案看到我正在学习 ASP.Net Core,我正在阅读大量网站(包括 docs.microsoft.com),我将IDbContextFactory代码放入其中,如上所示。 I removed that from my code and the error went away and everything built and created the migration.我从我的代码中删除了它,错误消失了,所有内容都构建并创建了迁移。

I am going to mark @alessalessio as the answer as I assume (have not tested it yet) that taking out the ILoggerFactory loggerFactory dependency within the AlmanacDbFactory constructor will do the trick as well.我将把@alessalessio 标记为答案,因为我认为(尚未测试过)在AlmanacDbFactory构造函数中取出ILoggerFactory loggerFactory依赖项也可以解决问题。

Design-time tools attempt to automatically find how your application creates instances of your DbContext type.设计时工具会尝试自动查找应用程序如何创建 DbContext 类型的实例。 If EF cannot find a suitable way to initialize your DbContext, you may encounter this error.如果 EF 找不到合适的方法来初始化您的 DbContext,您可能会遇到此错误。

Options: 1- Either create a parameterless constructor选项:1-要么创建一个无参数的构造函数

  public AlmanacDb() { }
  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {           
       optionsBuilder.UseSqlServer(_connString);
  }

  private readonly string _connString = "<your conn string>";

2- 2-

public AlmanacDb Create()
{
     var optionsBuilder = new DbContextOptionsBuilder<AlmanacDb>();
     optionsBuilder.UseSqlServer(connectionString);

     return new AlmanacDb(optionsBuilder.Options);
}

https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

If you have a separate project for context.如果您有一个单独的上下文项目。 set a startup project with the target project使用目标项目设置启动项目

dotnet ef migrations add InitialCreate -s .\src\WebUI\  -p .\src\Infrastructure\ --verbose

I had the same issue.我遇到过同样的问题。 My problem started when i changed my imeplementation of ApplicationUser to User with Guid Id.当我将 ApplicationUser 的实现更改为具有 Guid Id 的用户时,我的问题就开始了。

public class User : IdentityUser<Guid>

First I started getting some crazy errors and after setting my DbContext to:首先,我开始收到一些疯狂的错误,然后将我的 DbContext 设置为:

public class NgSchoolsContext : IdentityDbContext<User, IdentityRole<Guid>, Guid>

I started getting the "No parameterless constructor" error.我开始收到“无参数构造函数”错误。 What finally fixed it was changing the Roles configuration in Startup:最终修复它的是更改启动中的角色配置:

services.AddIdentityCore<User>() .AddEntityFrameworkStores<NgSchoolsContext>() .AddRoles<IdentityRole<Guid>>() .AddDefaultTokenProviders();

Notice the IdentityRole part.注意 IdentityRole 部分。 You don't need to implement a thing, just put it like that.你不需要实现一个东西,就这么说。 It should work out of the box.它应该是开箱即用的。 HOWEVER!!然而!! Your migrations WILL fail and you'll have to rebuild your db from start.您的迁移将失败,您必须从头开始重建您的数据库。 Entity can't handle the fact that all of his primary keys went from string(or whatever) to Guid and won't be able to update the database.实体无法处理他的所有主键都从字符串(或其他)到 Guid 并且无法更新数据库的事实。 Well, that is at least easier to solve.嗯,这至少更容易解决。 Drop database, delete all migrations, Add-Migration (new initial) and Update-Database.删除数据库,删除所有迁移,添加迁移(新初始)和更新数据库。 This would be so easy if for normal error message.如果是正常的错误消息,这将非常容易。

I had the same error "No parameterless constructor defined for type ..." while trying to adda migration.我在尝试添加迁移时遇到了同样的错误“没有为类型定义无参数构造函数......”。 Turns out that when running ef migrations entity framework passes on arguments in the startup project Program.cs The string[] args was removed for security reasons.事实证明,当运行ef migrations实体框架时,在启动项目 Program.cs 中传递参数时,出于安全原因删除了string[] args Adding this resolved the issue.添加这个解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架核心:没有为此 dbcontext 定义无参数构造函数 - Entity Framework Core: No parameterless constructor defined for this dbcontext Ef Core: Add-Migration Fail No parameterless constructor defined 错误 - Ef Core : Add-Migration Fail No parameterless constructor defined error 没有为此对象定义无参数构造函数 - No parameterless constructor defined for this object 实体框架核心:无法添加迁移:无参数构造函数 - Entity Framework core: Cannot add migrations: No parameterless constructor 无参数构造函数中的初始化(实体框架) - Initialization in a Parameterless Constructor (Entity Framework) 从数据库更新实体后发生错误:未为此对象定义无参数构造函数 - Error after updating Entity from Database: No parameterless constructor defined for this object automapper 中没有为此 object 定义无参数构造函数 - No parameterless constructor defined for this object in automapper 错误:未为此对象定义无参数构造函数 - Error: No parameterless constructor defined for this object 在mvc中没有为此对象定义无参数构造函数 - No parameterless constructor defined for this object in mvc MissingMethodException:没有为此对象定义无参数构造函数 - MissingMethodException: no parameterless constructor defined for this object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM