Setting up your DbContext for Entity Framework in .NET Core

Published: Sunday 29 December 2019

In-order to use Entity Framework successfully, you need to set your DbContext. But what exactly is it?

The DbContext is the relationship between the database and your application. You will configure your connection to the database and which entities you wish to query against inside the DbContext. You can set the entities by storing them as properties. The properties will have a type of DbSet which includes a generic type. Your entity type will fill the generic type.

So, how do we go about setting it up?

Setting up your DbContext

You will need to include the Microsoft.EntityFrameworkCore package into your application. This guide is for .NET Core, but if you are still using .NET Framework, the NuGet package is called EntityFramework.

Regardless of which package you are using, you will need to set up your class and ensure that it inherits the DbContext class.

For .NET Core users, configuring your application is quite simple. You just need to do these two things:

  • Add your connection string to your appsettings.json file
  • Specify your connection string by overriding the OnConfiguring method in DbContext

When adding your connection string, you need to specify a new key-value string inside the "ConnectionStrings" key. Here is an example of how your appsettings.json might look like:

{
	"ConnectionStrings": {
		"CinemaDbContext": "Server=myserver;Database=Cinema;Trusted_Connection=False;User Id=sa;Password=**********;ConnectRetryCount=3"
	}
}

Take a note of the key you've given for your connection string. In the above example, I've stated the key of my connection string as "CinemaDbContext".

The next task is to specify your connection string in your DbContext. As stated above, you can do that by overriding the OnConfiguring method in your DbContext.

You will need to do that by building your configuration file and using the GetConnectionString method to specify the key of your connection string.

Here is an example of how your DbContext might look like:

// CinemaDbContext.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
 
namespace EFMigrations
{
	public partial class CinemaDbContext : DbContext
	{
		public virtual DbSet<FilmEntity> Films { get; set; }

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			IConfigurationRoot configuration = new ConfigurationBuilder()
				 
				.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
				.AddJsonFile("appsettings.json")
				.Build();
			optionsBuilder.UseSqlServer(configuration.GetConnectionString("CinemaDbContext"));
		}
	}
}

Creating Entities for your DbContext

The next job is to create entities for your DbContext. Typically, it's common practice for entities to match the layout of your database tables. Above all, it will keep the naming between your application and database consistent. The entity class represents the table, and the properties inside your entity represent the columns.

It's at this point that you consider relationships. How do you set up a relationship between two entities in EF?

Inside your entity, you can create a public static OnModelCreating method that will do just that! This will store the relationship between two entities by using some Entity Framework methods. However, you must remember to call any OnModelCreating static methods inside your overridden OnModelCreating method for your DbContext.

What happens if you forget to do this? Well, your relationships and foreign keys will not be created in your database when you run the migration.

Here is a full example:

// CinemaDbContext.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
 
namespace EFMigrations
{
	public partial class CinemaDbContext : DbContext
	{
		public virtual DbSet<FilmEntity> Films { get; set; }

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			IConfigurationRoot configuration = new ConfigurationBuilder()

				.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
				.AddJsonFile("appsettings.json")
				.Build();
			optionsBuilder.UseSqlServer(configuration.GetConnectionString("CinemaDbContext"));
		}

		protected override void OnModelCreating(ModelBuilder builder)
		{
			FilmEntity.OnModelCreating(builder.Entity<FilmEntity>());
		}
	}
}
// FilmEntity.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
 
namespace EFMigrations
{
	public partial class FilmEntity
	{
		public virtual int Id { get; set; }

		public virtual string Name { get; set; }

		public virtual int CreatedYearId { get; set; }

		public virtual YearEntity CreatedYear { get; set; }

		public static void OnModelCreating(EntityTypeBuilder<FilmEntity> builder)
		{
			builder
				.HasOne(film => film.CreatedYear)
				.WithMany(createdYear => createdYear.CreatedFilms)
				.OnDelete(DeleteBehavior.NoAction)
				.HasPrincipalKey(createdYear => createdYear.Year)
				.HasForeignKey(film => film.CreatedYearId);
		}

	}
}
// YearEntity.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
 
namespace EFMigrations
{
	public partial class YearEntity
	{
		[Key]
		public virtual int Year { get; set; }

		public virtual ICollection<FilmEntity> CreatedFilms { get; set; }
	}
}