Tech Junkie Blog - Real World Tutorials, Happy Coding!: Hour 12 ASP.NET Core : Create The NothwindContext ( EntityFrameworkCore )

Wednesday, August 21, 2019

Hour 12 ASP.NET Core : Create The NothwindContext ( EntityFrameworkCore )

In our previous post we created the models for our Northwind Cafe application.  In this blog we will create the DbContext class which is the conduit between your entity classes and the database.  Think of it as a bridge that the database and the entity framework has to cross to get to each other.

Follow the steps below to create the NorthwindContext:

1. Create a class in Models folder call NorthwindContext























2. Type in the following code in the NorthwindContext class

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NorthwindCafe.Web.Models
{
    public class NorthwindContext : DbContext
    {
        public NorthwindContext(DbContextOptions<NorthwindContext> options)
            :base(options)
        { }

        public DbSet<Product> Products { set; get; }
        public DbSet<Category> Categories { set; get; }
        public DbSet<Order> Orders { get; set; }

        public DbSet<OrderDetail> OrderDetails { get; set; }

    }
}


Make sure you import the namespace Microsoft.EntityFrameworkCore. I will go over the code above line by line.

public class NorthwindContext : DbContext

This means the NorthwindContext is a subclass of the DbContext class

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

The NorthwindContext constructor tells .NET to pass the DbContextOptions to the base class. We need this because we will add the NorthwindContext in the Startup.cs class in another post.
 
        public DbSet<Product> Products { set; get; }
        public DbSet<Category> Categories { set; get; }
        public DbSet<Order> Orders { get; set; }

        public DbSet<OrderDetail> OrderDetails { get; set; }

The DbSet represents the tables and entities that will be created for this context. That's about it, the next few posts will go over how to add the NorthwindContext to our application and create our new Northwind database from scratch.

No comments:

Post a Comment

Search This Blog