Migrations Database Dotnet Core 2.0

สร้าง Models และ Context เเล้วรันคำสั่ง

  • Add-Migration init — จะทำการ Gen Code ส่วน Migrations เพื่อรอ
  • Update-Database — เป็นคำสั่งเพื่อทำการ Migrations ขึ้น Database ตาม ConnectionString
  • Update-Database -Context ContextName
  • Add-Migration -Context ContextName

— — — — — — — — — — — — — — — — — -

dotnet ef migrations add InitialCreate

dotnet ef database update

— — — — — — — — — — — — — — — — —

ตัวอย่าง Code COntext

using WebApplication3.Models;
using Microsoft.EntityFrameworkCore;
namespace WebApplication3.Data
{
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<DistrictModel> Districts { get; set; }
public DbSet<User> users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().ToTable(“Course”);
modelBuilder.Entity<Enrollment>().ToTable(“Enrollment”);
modelBuilder.Entity<Student>().ToTable(“Student”);
modelBuilder.Entity<User>().ToTable(“user”);
}
}
}

ตัวอย่าง Model

using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;
namespace WebApplication3.Models
{
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
}

FROM microsoft/aspnetcore-build:2.0 AS build-env
# Copy csproj and restore as distinct layers
COPY *.csproj ./
COPY . /app
WORKDIR /app
RUN dotnet restore
#FROM microsoft/dotnet:latest
RUN dotnet ef database update
# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
# Build runtime image
FROM microsoft/aspnetcore:2.0
WORKDIR /app
COPY — from=build-env /app/out .
ENTRYPOINT [“dotnet”, “WebApplication3.dll”]

อย่าลืมมมม *.csproj

<ItemGroup>
 <DotNetCliToolReference Include=”Microsoft.VisualStudio.Web.CodeGeneration.Tools” Version=”2.0.0" />
 <DotNetCliToolReference Include=”Microsoft.EntityFrameworkCore.Tools” Version=”2.0.0" />
 <DotNetCliToolReference Include=”Microsoft.EntityFrameworkCore.Tools.DotNet” Version=”2.0.0" />
 </ItemGroup>