Categories
.NET Core

Entity Framework Code First Approach With .NET Core

In this post we will look at how we can use Entity Framework code first approach with .NET Core application.

Introduction

Entity Framework is the most popular Object Relational Mapper (ORM) built for .NET framework. It enables developers to work with different databases using .NET objects eliminating the need to write lower level database access codes.

Adding Entity Framework

First of all, define a context class named “MyDbContext.cs” which will derive from DbContext class.

//MyDBContext.cs
public class MyDbContext: DbContext
    {

    }

An instance of DbContext represents a session with the database which can be used to query and persist instances of your entities.

The default constructor should be defined as:

//MyDBContext.cs
public MyDbContext(DbContextOptions<MyDBContext> options)
            : base(options)
        { }

Next, define your entity class in “User.cs” file. The entity class usually represents your Database Table.

//User.cs
public class User
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime UpdatedAt { get; set; }
    }

Now, we add the User entity in our context class as DbSet.

Truenary Solutions

The DbSet class represents an entity set that can be used for create, read, update, and delete operations in the database.

//MyDBContext.cs

    public class MyDBContext: DbContext
    {
        public MyDBContext(DbContextOptions<MyDBContext> options)
            : base(options)
        { }

        DbSet<User> Users { get; set; }
    }

Getting Connection String

In order for the entity framework to communicate with any database, it needs the database connection credentials. So, let’s create a helper class to get database connection info for our context:

Add a class “DbConfig.cs” as:

public class DbConfig
    {
        public static string GetConnectionString() {
            
            var server = System.Environment.GetEnvironmentVariable("DB_HOST");
            var name = System.Environment.GetEnvironmentVariable("DB_NAME");
            var user= System.Environment.GetEnvironmentVariable("DB_USER");
            var password = System.Environment.GetEnvironmentVariable("DB_PASSWORD");

            var connection = $"Server={server};Database={name};User Id={user};Password{password}";
            return connection;
        }
    }

This class basically creates a connection string based on the database info which should be stored as environment variables.

Next, let’s register our context through the ConfigureServices method in our “Startup.cs” class.

Registering Database Context

Depending upon the database type that you choose to use, this registration process can be different. For example you setup differently for MS-SQL server database as compared to My-SQL server database.

Registering MS-SQL Database Context

//Startup.cs

// This method gets called by the runtime. 
// Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<MyDbContext>
                (options => options.UseSqlServer(DbConfig.GetConnectionString()));
        }

Registering My-SQL Database Context

Microsoft doesn’t have official package to support MySQL data provider for EF Core (yet). However, there is an open source package corePomelo.EntityFrameworkCore.MySql maintained by Pomelo Foundation for this purpose.

//Startup.cs

public void ConfigureServices(IServiceCollection services)
        {            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<MyDbContext>
                (options => options.UseMySql(DbConfig.GetConnectionString()));          
        }

Running Migrations

Now that we have registered the entity framework database context, it is time to create database.

In a command prompt, run the following command:

dotnet ef migrations add InitialCreate

The migrations command scaffolds a migration to create the initial set of tables for the model.

This command will generate couple of files inside the “Migrations” folder:

  • Initial Create (Migration file with timestamp)
  • ModelSnapshot

So far we have only generated migration scripts and database isn’t created yet. Finally now we create the database with the following command:

dotnet ef database update

The database update command creates the database and applies the new migration to it. If you have provided the correct database connection credentials, uou should now have a new database that has the table “User” in it.

Conclusion

In this post we learned how to set Entity Framework Code First with .NET Core app. We saw how we can define database context, table entity and register database context for MS-SQL and My-SQL databases.

Next post will cover:

Updating Entity Model, Adding Foreign Key Relationships and Reverting/Removing Migrations.

Leave a Reply

Your email address will not be published. Required fields are marked *