Skip to content

Errors when using dotnet ef anycommand #5304

Closed

Description

@Bartmax

When running dotnet ef migrations list (or any command actually) I get this error (ignore the warnings):

[xxx.Web]: dotnet ef migrations list
Project xxx.Web (.NETCoreApp,Version=v1.0) will be compiled because inputs were modified
Compiling xxx.Web for .NETCoreApp,Version=v1.0
C:\xxx\xxx\xxx\xxx\src\xxx.Web\project.json(82,22): warning DOTNET1015: The 'publishExclude' option is deprecated. Use 'publishOptions' instead.
Compilation succeeded.
    3 Warning(s)
    0 Error(s)
Time elapsed 00:00:03.2634767
C:\xxx\xxx\xxx\xxx\src\xxx.Web\project.json(78,15): warning DOTNET1015: The 'exclude' option is deprecated. Use 'exclude' within 'compile' or 'embed' instead.
C:\xxx\xxx\xxx\xxx\src\xxx.Web\project.json(4,26): warning DOTNET1015: The 'compilationOptions' option is deprecated. Use 'buildOptions' instead.

System.NullReferenceException: Object reference not set to an instance of an object.
   at xxx.Web.Startup.<>c.<ConfigureServices>b__3_1(DbContextOptionsBuilder options)
   at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ClosedIEnumerableService.CallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.TransientCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.Design.DbContextOperations.FindContextTypes()
   at Microsoft.EntityFrameworkCore.Design.DbContextOperations.FindContextType(String name)
   at Microsoft.EntityFrameworkCore.Design.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.GetMigrations(String contextType)
   at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsListCommand.Execute(CommonOptions commonOptions, String context, String startupProject, String environment, Action`1 reportResultsAction)
   at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsListCommand.<>c__DisplayClass0_0.<Configure>b__0()
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
Object reference not set to an instance of an object.

dbcontext:

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

        }
        public ApplicationDbContext(DbContextOptions options)
        :base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
             // ...
        }
       // ....
}

startup:

services.AddEntityFramework()
                .AddEntityFrameworkSqlServer()
                .AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Program.Configuration["Data:DefaultConnection:ConnectionString"]));

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

dotnet info:

dotnet --info
.NET Command Line Tools (1.0.0-preview1-002700)

Product Information:
 Version:     1.0.0-preview1-002700
 Commit Sha:  0336f6bb34

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.10586
 OS Platform: Windows
 RID:         win10-x64

Activity

  1. added this to the 1.0.0 milestone on May 9, 2016
  2. natemcmaster commented on May 9, 2016

    @natemcmaster
    Contributor

    @Bartmax thanks for the stack trace. This shows that the NRE comes from user code, not ef. When EF invokes startup, something inside is null. This could be that either EF invokes Startup without all the right parameters, or the user code isn't loading something correctly at design time. Based on what provided, my guess is the problem is this expression Program.Configuration["Data:DefaultConnection:ConnectionString"]. Can you also include "Program"?

  3. Bartmax commented on May 9, 2016

    @Bartmax
    Author

    sure! makes sense... I think this static is bad :)

    public static class Program {
            public static IConfigurationRoot Configuration { get; set; }
            public static void Main(string[] args) {
                var config = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json", optional: false)
                    .AddJsonFile("hosting.json", optional: true)
                    .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                    .AddUserSecrets()
                    .Build();
                Configuration = config;
    
                var host = new WebHostBuilder()
                            .UseKestrel()
                            .UseContentRoot(Directory.GetCurrentDirectory())
                            .UseConfiguration(config)
                            .UseIISIntegration()
                            .UseStartup<Startup>()
                            .Build();
                host.Run();
            }
        }
    
  4. natemcmaster commented on May 9, 2016

    @natemcmaster
    Contributor

    Bingo. EF doesn't run Program.Main. "dotnet ef" will only invoke the Startup class. If you initial Configuration somewhere else (such as a static constructor on Program), this should solve the NRE.

    FYI - we hope to sort out this interaction with ASP.NET hosting for our RTM release. See #4546.

  5. Bartmax commented on May 9, 2016

    @Bartmax
    Author

    @natemcmaster static constructor on program?

  6. natemcmaster commented on May 9, 2016

    @natemcmaster
    Contributor

    To clarify, I mean you could use a static constructor. But as long as Configuration is initialized somehow in these steps, it doesn't matter how you want to structure your code.

    How EF calls startup: https://github.com/aspnet/EntityFramework/blob/96628d58a56865f8f6650e3fa0e970f1bdd11a2e/src/Microsoft.EntityFrameworkCore.Tools.Core/Design/Internal/StartupInvoker.cs

  7. natemcmaster commented on May 9, 2016

    @natemcmaster
    Contributor

    Closing as a duplicate of #4546. @Bartmax feel free to re-open if you still can't get this to work.

  8. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions