สร้างคลาส Data\SeedData.cs
Data\SeedData.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; using WebApi.Data.Models; namespace WebApi.Data { public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var context = new ApplicationDbContext( serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>())) { // Look for any movies. if (context.Movie.Any()) { return; // DB has been seeded } context.Movie.AddRange( new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-2-12"), Genre = "Romantic Comedy", Price = 7.99M }, new Movie { Title = "Ghostbusters ", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M }, new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M }, new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M } ); context.SaveChanges(); } } } } |
บรรทัดที่ 9 : SeedData
เป็น Static คลาส
บรรทัดที่ 11 : Initialize()
เป็น Static ฟังก์ชัน
บรรทัดที่ 17 : ตรวจสอบว่าตาราง Movie มีข้อมูลมั๊ย ถ้ามีก็ไม่ต้อง Seed
Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using WebApi.Data; namespace WebApi { public class Program { public static void Main(string[] args) { //CreateWebHostBuilder(args).Build().Run(); var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<ApplicationDbContext>(); context.Database.Migrate(); SeedData.Initialize(services); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } } |
เปลี่ยนจาก Seed ที่ Startup.cs มา Seed ที่ Program.cs
รันกด F5
เสร็จแล้วกลับมาดูที่ Database จะมีข้อมูลเพิ่มเข้ามา (แต่หน้าเว็บยังไม่เห็นอะไร)