Index:
- Example entity model
- Install NuGet packages
- Create context class
- Update Startup.cs
- Example connection string
- Add-Migration
- Update-Database
- Seed data
Example entity model
using System.ComponentModel.DataAnnotations;
namespace MyProject.Models
{
public class Customer
{
[Key]
public long CustomerId { get; set; }
public string Name { get; set; }
public DateTime? FirstPurchaseDate { get; set; }
}
}
Read about the [Key]
annotation and others here
Install NuGet packages (the Identity packages are only necessary if your app is managing identities, I think)
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
Create your context class that inherits from DbContext. I like to put my context class in a folder named “Data” at the root of my project.
using Microsoft.EntityFrameworkCore;
using MyProject.Models;
namespace MyProject.Data
{
public class ApplicationDbContext : DbContext
{
public MyProjectDbContext(DbContextOptions<MyProjectDbContext> options) : base(options)
{
}
// Add DbSet for each entity class
public DbSet<Customer> Customer { get; set; }
}
}
Call services.AddDbContext<>(...);
in Startup.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using MyProject.Data;
namespace MyProject
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddDbContext<MyProjectDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ...)
{
// ...
}
}
}
Example appsettings.json connection string (the database it points to doesn’t need to exist, but the connection string needs to exist for Add-Migration
to work )
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
}
TODO: Add-Migration
TODO: Update-Database
TODO: Initialization code, like seed data
Leave a Reply