Modelを作成する
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
[Required]
public int CourseId { get; set; }
public Course Course { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public ICollection<Student> Students { get; set; }
}
DbContextを作成する
public class StudentDbContext : DbContext
{
public StudentDbContext (DbContextOptions<StudentDbContext> options)
: base(options)
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
Startup.csでDIコンテナにサービスを登録する
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<StudentDbContext>(options=>
options.UseSqlServer(Configuration.GetConnectionString("StudentDb")));
}
Add-Migration マイグレーション名
Update-Database