entity framework 6 - seeding database throws System.NullReferenceException

c# code-first entity-framework-6 entity-framework-core

Question

I'm using .net core 2 and entityframework 6.2. I'm trying to seed database with some needed base data.

  1. I didn't find the Database.SetInitializer method. So I googled and found another way to seed my database in Main method of Program class (as shown below).
  2. I used below code to seed my database but when executing SaveChange method of DbContext, always I get NullReferenceException error.
  3. I'm using the same database as Identity uses. Does it affect the result?

Program class:

public class Program
{
    public static void Main(string[] args)
    {
        //BuildWebHost(args).Run();

        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                context.Provinces.Add(new Models.Province
                {
                    ID = 1,
                    Name = "TEST"
                });
                context.SaveChanges(); // <= ERROR
                //DbInitializer.Initialize(context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occured while seeding the database.");
            }
        }

        host.Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

Exception:

Message: "Object reference not set to an instance of an object."
Source: "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore"
StackTrace:
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.System.IObserver<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.OnNext(KeyValuePair`2 keyValuePair)
   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
   at Microsoft.EntityFrameworkCore.Internal.CoreLoggerExtensions.SaveChangesFailed(IDiagnosticsLogger`1 diagnostics, DbContext context, Exception exception)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
   at Invitation.Program.Main(String[] args) in d:\Projects\Invitation\Invitation\Program.cs:line 29
InnerException: null

Startup class:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddCustomIdentity()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddTransient<IdentityErrorDescriber, FaIdentityErrorDescriber>();

        services.ConfigureCustomApplicationCookie();

        services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

        services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Account/Manage");
                options.Conventions.AuthorizePage("/Account/Logout");
            });

        var connection = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connection));

        services.AddSingleton<IEmailSender, EmailSender>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();

        app.UseMvc();
    }
}

ApplicationDbContext class:

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

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

    public DbSet<Province> Provinces { get; set; }
}

B.W. I'm using EntityFramework 6.2.0 & Microsoft.EntityFrameworkCore.Tools 2.1.1 (maybe useful info)

Thanks for spending time.

1
1
7/23/2018 6:26:42 AM

Accepted Answer

OK! I found the reason. In Main method when I'm creating a new entity of type Province, assigning value to its key parameter causes the error. This solves the problem:

context.Provinces.Add(new Models.Province
{
     //ID = 1,
     Name = "TEST"
});

But yet I'm really angry because the exception thrown doesn't show the real error!

0
7/23/2018 8:15:13 AM

Popular Answer

Use this code:

public class Program
{
    public static void Main(string[] args)
    {
        //BuildWebHost(args).Run();

        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                using (var context = new ApplicationDbContext(
                services.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
                {
                    context.Provinces.Add(new Models.Province
                    {
                        ID = 1,
                        Name = "TEST"
                    });
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occured while seeding the database.");
            }
        }

        host.Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

Code from : https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-2.0&tabs=aspnetcore2x



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow