How to seed a database from the context

178 Views Asked by At

I'm doing an ASP.NET Core MVC demo project for a job interview. The book I'm using shows me how to wire up an MVC project from the empty project template. I'm calling Database.EnsureCreated() in the constructor of the database context class to create the MS SQL Server Express database when the app runs. This is good enough for the demo project as it only needs to run locally. However, what is the best way to seed the database in this scenario? I thought of doing the following:

public class DemoDataContext : DbContext
{
    public DbSet<Item> Items { get; set; }

    public DemoDataContext(DbContextOptions<DemoDataContext> options) : base(options)
    {
        Database.EnsureCreated();

        if (!Items.Any())
        {
            Items.Add(new Item
            {
                Id = 1,
                Name = "Item" 
            });
        }

        SaveChanges();
    }
}

However, I'm getting null warnings on the DbSet methods, so I don't know if there's a more correct way to do this. I do want to keep things simple though.

1

There are 1 best solutions below

0
Qing Guo On

to create the MS SQL Server Express database when the app runs.

You can refer to Part 4, add a model to an ASP.NET Core MVC app Part 5, work with a database in an ASP.NET Core MVC app

public class DemoDataContext : DbContext
    {
        public DemoDataContext (DbContextOptions<DemoDataContext> options)
            : base(options)
        {
        }

        public DbSet<Item> Items { get; set; }
    }

then Seed the database like: this and Add the seed initializer

Besides, you can raed Data Seeding to know more.