- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.Sqlite
<ItemGroup>
<DotNetCliToolReferenceInclude="Microsoft.EntityFrameworkCore.Tools.DotNet"Version="1.0.0" />
</ItemGroup>
namespace ModelBindingApp.Models
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public char Gender { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
namespace ModelBindingApp.Models
{
public class AppDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
}
}
"ConnectionStrings": {
"DefaultConnection": "Data Source=ModelBindingApp.db"
},
// other configuration
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();
}
}
}
}
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);
dotnet ef migrations add InitialCreate