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.
Add a new project of type class library (.NET Core), named "EntityFrameworkFactory".
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; }
- }
- }
Create a new class in the project to be the dbContext factory, which will create your database, named SampleContextFactory. This class will inherit from the IDbContextFactory, with the type of the created context.
- 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".
Execute this command (you may change the test to any name as you wish).
Execute the last command.
Congratulations! You have your Entity Framework Core database set up.