Skip to content

Instantly share code, notes, and snippets.

@MJeorrett
Last active May 9, 2017 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MJeorrett/00816c43729f462791bb831b989029da to your computer and use it in GitHub Desktop.
Save MJeorrett/00816c43729f462791bb831b989029da to your computer and use it in GitHub Desktop.
Quickstart for EntityFrameworkCore

Install Dependencies

  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.Sqlite

Add following to .csproj file:

<ItemGroup>
     <DotNetCliToolReferenceInclude="Microsoft.EntityFrameworkCore.Tools.DotNet"Version="1.0.0" />
</ItemGroup>

Create a model class

namespace ModelBindingApp.Models
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public char Gender { get; set; }
    }
}

Create a dbContext class

using Microsoft.EntityFrameworkCore;
namespace ModelBindingApp.Models
{
    public class AppDbContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
        
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }
    }
}

Add Connection String to appsettings.json

"ConnectionStrings": {
    "DefaultConnection": "Data Source=ModelBindingApp.db"
},
// other configuration

Create DbInitialisationHelper class

using Microsoft.EntityFrameworkCore;
using ModelBindingApp.Models;
using System.Linq;

namespace ModelBindingApp.Data
{
    public class DbInitialisationHelper
    {
        public static void InitialiseDb(AppDbContext appDbContext)
        {
            // ensure that Db is create and migrated
            appDbContext.Database.Migrate();

            // Add a seed record if there are no records
            if (!appDbContext.Employees.Any())
            {
                var employee = new Employee
                {
                    Name = "Matthew Jeorrett",
                    Gender = 'M'
                };

                appDbContext.Add(employee);
                appDbContext.SaveChanges();
            }
        }
    }
}

Configure Startup

At the begining of ConfigureServices method add:

services.AddDbContext<AppDbContext>(options =>
     options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

Add the AppDbContext to the Configure method paramters:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, AppDbContext appDbContext)
{
     // method body
}

At the end of the Configure method add:

DbInitialisationHelper.InitialiseDb(appDbContext);

Create Migration

dotnet ef migrations add InitialCreate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment