Create the model & context

Create the model Student

1) open the project we just created in Visual Studio

2) In the project root directory create a Student class as shown:

namespace EFGetStarted
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsEnrolled { get; set; }
    }
}

An entity framework model is nothing but a plain old C# object (POCO)

A real project model will have a lot many properties, but we have just shown a few here to for brevity. A model can also contain navigation properties to other models which we will discuss later.

Create the context MyContext

Let us create an application context called MyContext as given below, in the root of the project

using Microsoft.EntityFrameworkCore;

namespace EFGetStarted
{
    public class MyContext: DbContext
    {        
        public DbSet<Student> Students { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            var server = "(localdb)";
            var instance = "mssqllocaldb";
            var database = "CollegeDB";
            var authentication = "Integrated Security = true";

            var conString = $"Data Source={server}\\{instance}; Initial Catalog={database};{authentication}";

            options.UseSqlServer(conString);            
        }
    }
}

What is a DbContext ?

A DbContext instance represents a session with the database and can be used to query and save instances of your entities.

  • DbContext is a combination of the Unit Of Work and Repository patterns.

  • Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance.

  • Typically, you create a class that derives from DbContext

  • This class then contains DbSet<TEntity> properties for each entity in the model.

  • We Override the OnConfiguring(DbContextOptionsBuilder) method to configure the database

  • We can also configure other options to be used for the context.

  • The model is discovered by running a set of conventions over the entity classes found in the DbSet<TEntity> properties on the derived context.

  • To further configure the model that is discovered by convention, you can override the OnModelCreating(ModelBuilder) method.

  • It also has change tracking capabilities which we will discuss later

A DbContext instance represents a session with the database. The model is discovered by running a set of conventions over the entity classes found in the DbSet.

Last updated