nam vo
nam vo

Reputation: 3447

Entity Framework core: Cannot add migrations: No parameterless constructor

My data project reference: (Entity Framework Core)

    <Project Sdk="Microsoft.NET.Sdk">    
      <PropertyGroup>
        <TargetFramework>netcoreapp1.1</TargetFramework>
      </PropertyGroup>    
      <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
        <ProjectReference Include="..\Butv.Core\Butv.Core.csproj" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" PrivateAssets="All" />      
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.0.0" />    
      </ItemGroup>
      <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />  
      </ItemGroup>
      <ItemGroup>
        <Folder Include="Migrations\" />
      </ItemGroup>
    </Project>

The db Context:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {  ....
     }
}
public class ApplicationUser : IdentityUser
{
}

Every time I try command

dotnet ef migrations add Init --verbose

, I get the error. It's used to work fine before I separate the Data project from the main project.

Microsoft.EntityFrameworkCore.Design.OperationException: No parameterless constr uctor was found on 'ApplicationDbContext'. Either add a parameterless constructo r to 'ApplicationDbContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'ApplicationDbContext'. ---> System.Mi ssingMethodException: No parameterless constructor defined for this object. at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOn ly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Bo olean& bNeedSecurityCheck)

Upvotes: 4

Views: 9703

Answers (3)

paulsm4
paulsm4

Reputation: 121869

For whatever it's worth, I encountered this error in ASP.Net Core 2.1/EF because of a syntax error in my "appsettings.json":

  • BAD APPSETTINGS:

    {
      "ConnectionStrings": {
        "DefaultConnection": "\"Server=(LocalDb)\\\\MSSQLLocalDB;Database=demoangulardatabase;",
        "Trusted_Connection=True;MultipleActiveResultSets=true\""
      },
      ...
    
  • Failed "migrate" command:

    dotnet ef migrations add initialMigration -c ApplicationDbContext -v
    ...
    Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'ApplicationDbContext'. 
    Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see  https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time. ---> 
    System.MissingMethodException: No parameterless constructor defined for this object.
    ...
    
  • Corrected appsettings.json:

    "ConnectionStrings": {
      "DefaultConnection": 
        "Server=(LocalDb)\\MSSQLLocalDB;Database=demoangulardatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    

After fixing the corrupted appsettings.json, dotnet ef migrations add initialMigration -c ApplicationDbContext -v ran perfectly.

Upvotes: 0

Yervand Abrahamian
Yervand Abrahamian

Reputation: 292

I had the same problem. I have get it on the project that was migrates normally. From some point it start giving me this error. The problem was in Startup project selection. Select a project as startup in where you configured Entity Framework to use as a service.

This can help

Upvotes: 12

Steve
Steve

Reputation: 9593

It's exactly like the error says. You either need a parameterless constructor on your DbContext class (which you essentially can't do), or implement IDbContextFactory.

The method I used was to create an implementation of IDbContextFactory and return an instance of my DbContext from the Create method, like so:

public class ApplicationDbContext : DbContext<ApplicationDbContext>
{
    // DbContext code as normal
}

public class ApplicationDbContextFactory : IDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext Create(DbContextFactoryOptions options)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        return new ApplicationDbContext(optionsBuilder.Options);
    }
}

Note you have to create a DbContextOptionsBuilder to pass through to the DbContext, however since migrations do not actually hit the database and just read your entity classes I don't believe you need to actually configure any options, except for possibly the Database Provider as I've run into issues with migration code generated that worked for one provider but not another.

Now when you run the migration, EF should automatically find the Factory class and use that to create a new DbContext.

Upvotes: 2

Related Questions