In this write-up, I will explain how to easily and quickly set up your database using Entity Framework Core in a .NETCore project using the factory pattern to connect your entities to your database.
Steps to reproduce:
Make sure to have the respective NuGet packages inside this project.
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.SqlServer (to connect to SQL Server)
- Microsoft.EntityFrameworkCore
Add a new folder for models (Where you would put your entities).
Add a new class inside this folder and include some properties. This class will be our unique model used for this example. This class must have one property with the Key attribute. (One entity as an example with two properties).
- using System.ComponentModel.DataAnnotations;
- namespace EntityFrameworkFactory.Models
- {
- public class ModelSample
- {
- [Key]
- public int IdModelSample { get; set; }
- public string DescriptionModelSample { get; set; }
- }
- }
Add a new class in the root of this project, named SampleContext. This class will be our context class that will be used to connect with the database. This class will inherit from DbContext.
Declare the sample model created as a dbset and set up the constructor.
- using Microsoft.EntityFrameworkCore;
- using EntityFrameworkFactory.Models;
- namespace EntityFrameworkFactory
- {
- public class SampleContext : DbContext
- {
- public SampleContext(DbContextOptions<SampleContext> options) : base(options)
- {
- }
- public DbSet<ModelSample> SampleClass { get; set; }
- }
- }
- using Microsoft.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore.Infrastructure;
- namespace EntityFrameworkFactory
- {
- public class SampleContextFactory : IDbContextFactory<SampleContext>
- {
- public SampleContext Create(DbContextFactoryOptions options)
- {
- var optionsBuilder = new DbContextOptionsBuilder<SampleContext>();
- optionsBuilder.UseSqlServer("Data Source=YOUR DATA SOURCE;");
- return new SampleContext(optionsBuilder.Options);
- }
- }
- }
At this point, you have to open the Package Manager Console (Tools > NuGet Package Manager > Package Manager Console) and set the default project to "EntityFrameworkFactory".
- add-migration test
- Update-Database

abdelkrim Tabet AoulPosted Jan 5, 2021, 9:47 PM
Hi, let's assume we have WPF a project with mulptiple projects, i want to use dbcontext in a separate class library to avoid circular dependency with main project, if Context Factory can help us in this case?
Tridip BhattacharjeePosted Mar 16, 2018, 4:21 AM
Mostly people use factory to change from one type to another dynamically. so please extend this article and show us how we can change connection string with your factory approach. thanks
Tridip BhattacharjeePosted Mar 15, 2018, 3:40 AM
HI, you did not mention why you have taken approach for dbContext factory ? your objective is not clear. your approach will help us to change db connection easily ?
Naresh SinghalPosted Mar 14, 2018, 11:50 PM
Awesome...............