question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

IDesignTimeDbContextFactory Constructor with parameter

See original GitHub issue

I implement IDesignTimeDbContextFactory for dotnet ef migrations add. My current code is:

    public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<AppDbContext>();
            builder.UseSqlServer("Server=10.0.0.73\\MSSQLSERVER2016;Database=OpPISWebDevelopment;User Id=oppisweb;Password=oppisweb;Max Pool Size=10;Connection Timeout=100000;");

            return new AppDbContext(builder.Options);
        }
    }

But I don’t want hard coded ConnectionString. I tried like this:

    public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        private IConfiguration config;
        public ApplicationDbContextFactory(IConfiguration config)
        {
            this.config = config;
        }
        public AppDbContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<AppDbContext>();
            builder.UseSqlServer(this.config["ConnectionString"]);

            return new AppDbContext(builder.Options);
        }
    }

but I get error:

System.MissingMethodException: No parameterless constructor defined for this object. at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor) 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.CreateContextFromFactory(Type factory) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_0.<FindContextTypes>b__3() at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func1 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.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_01.<Execute>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) No parameterless constructor defined for this object.

when executed dotnet ef migrations add

How to get connection string from appsettings.json?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:9
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

7reactions
benrherecommented, Mar 8, 2018

I was finally able to figure this out. There were a few things that tripped me up:

To Start:

C:\Users\ben.rubinger\Desktop\EF Migrations Help\EF Migrations Help>dotnet ef migrations add new info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]

      User profile is available. Using 'C:\Users\ben.rubinger\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.0.1-rtm-125 initialized 'MyDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
Your target project 'EF Migrations Help' doesn't match your migrations assembly 'Data'. Either change your target project or change your migrations assembly.
Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("EF Migrations Help")). By default, the migrations assembly is the assembly containing the DbContext.
Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.

C:\Users\ben.rubinger\Desktop\EF Migrations Help\EF Migrations Help>

From here, I moved into the data project directory: C:\Users\ben.rubinger\Desktop\EF Migrations Help\Data>dotnet ef migrations add new

No executable found matching command "dotnet-ef"

This was because I didn’t have:

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />
  </ItemGroup>

in the relevant CSProj.

After I did this:

C:\Users\ben.rubinger\Desktop\EF Migrations Help\Data>dotnet ef migrations add new

Startup project 'Data.csproj' targets framework '.NETStandard'. There is no runtime associated with this framework, and projects targeting it cannot be executed directly. To use the Entity Framework Core .NET Command Line Tools with this project, add an executable project targeting .NET Core or .NET Framework that references this project, and set it as the startup project using --startup-project; or, update this project to cross-target .NET Core or .NET Framework.

C:\Users\ben.rubinger\Desktop\EF Migrations Help\Data>

Note that my solution did not involve following this advice. Instead, I finally figured out that I had to set the startup project: C:\Users\ben.rubinger\Desktop\EF Migrations Help\Data>dotnet ef migrations add new --startup-project “…\EF Migrations Help”

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\ben.rubinger\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.0.1-rtm-125 initialized 'MyDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
The name 'new' is used by an existing migration.

and it finally worked! It seemed counterintuitive that I need to run the command from the data directory, and point it to the original webapp directory, yet this gave me success. I’m posting this here in case others hit this. I struggled a bit with the bits and pieces of documentation.

Update: while the above is true for the sample project, for my actual project I had a last hurdle. My data project was targeting .netcoreapp2.0, and I got an error stating “The specified framework ‘Microsoft.NETCore.App’, version ‘2.0’ was not found”. I had to switch to .netstandard2.0 to finally get it working. Quite a few hurdles. I didn’t think this was a very strange scenario I was trying to achieve.

5reactions
ajcvickerscommented, Aug 18, 2017

@MaklaCof The factory is not, by design, resolved from the service provider. The way to get your configuration into the factory is to duplicate or refactor and re-use the code you have in Main that sets up your configuration. In fact, if you factor this out appropriately into a BuildWebHost method that is just about configuration and not about running the application, then you should not need to have a factory at all. For more information, see: https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/

Read more comments on GitHub >

github_iconTop Results From Across the Web

Pass arguments to IDesignTimeDbContextFactory of EF Core
i want to be able to update different database with the use of arguments. i've tried. dotnet ef database update "Accept". dotnet ef...
Read more >
Design-time DbContext Creation - EF Core
In this article. From application services; Using a constructor with no parameters; From a design-time factory; Args. Some of the EF Core ...
Read more >
IDesignTimeDbContextFactory<TContext> Interface
A factory for creating derived DbContext instances. Implement this interface to enable design-time services for context types that do not have a public ......
Read more >
Implement IDesignTimeDbContextFactory with ...
Implement this interface to enable design-time services for context types that do not have a public default constructor. At design-time, derived ...
Read more >
IDesignTimeDbContextFactory and Dependency Injection
In ASP.NET Core, this is determined by an special environment variable, ASPNETCORE_ENVIRONMENT . We're also going to want to plug in environment ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found