bflynnigan
bflynnigan

Reputation: 236

ApplicationDbContext Object reference not set to an instance of an object

I am trying to seed data into my Sqlite Database with an ASP.Net Core MVC app. Everything works fine until the command:

context.SaveChanges()

When this is fired an "Object reference not set to an instance of an object" is thrown, despite already having Added to the context without issue beforehand. Here is the suspect code:

public class Seeder
    {
        private ApplicationDbContext context;
        public Seeder(ApplicationDbContext _context)
        {
            context = _context;
        }
        //populate the database with the static items
        public void SeedData()
        {
            //jump out if data already exists
            if(context.HomeTypes.Count() != 0)
            {
                return;
            }

            //build the home types
            HomeType basic = new HomeType
            {
                home_type_id = 0,
                name = "Town House",
                capacity = 2,
                home_image_src = "changeThisLater"
            };
            context.HomeTypes.Add(basic);

            context.SaveChanges();

        }
    }

Here is where the seeder class is called:

public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            //seed the database when the app starts up
            using(var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<ApplicationDbContext>();
                    Seeder seeder = new Seeder(context);
                    seeder.SeedData();
                }catch(Exception e)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(e, "An error occured while seeding the db");
                }
            }

            //run
            host.Run();

        }

Here is a photo of my error message:

Upvotes: 1

Views: 1960

Answers (1)

bflynnigan
bflynnigan

Reputation: 236

Resolved!

The problem was with my ID's. In this seeder I set the value of home_type_id to 0. EF Core auto generates ID's so this was causing a problem and having my ID's be added as -2175267 (or something crazy like that).

The fix was simply to add:

 //prevent auto generation of the id feilds
 builder.Entity<Role>().Property(m => m.role_id).ValueGeneratedNever();
 builder.Entity<HomeType>().Property(m => m.home_type_id).ValueGeneratedNever();

To my ApplicationDbContext in the OnModelCreating function, and it works groovy now

Upvotes: 1

Related Questions