โปรเจ็กส์แบบ WebApi นี้ ทำการคอนฟิกค่าเกี่ยวกับดาต้าเบสไว้ที่ Startup.cs
แต่ทำการ Seed ที่ Program.cs
สร้างโปรเจ็กส์แบบ WebApi (ด้วย Visual Studio 2017)
สร้างโฟลเดอร์ Data
สร้างโฟลเดอร์ Data\Models
สร้างคลาส Data\Models\ApplicationUser.cs
Data\Models\ApplicationUser.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 |
using System; using System.ComponentModel.DataAnnotations; namespace WebApi.Data.Models { public class ApplicationUser { public ApplicationUser() { } [Key] [Required] public string Id { get; set; } [Required] [MaxLength(128)] public string UserName { get; set; } [Required] public string Email { get; set; } public string DisplayName { get; set; } public string Notes { get; set; } [Required] public int Type { get; set; } [Required] public int Flags { get; set; } [Required] public DateTime CreatedDate { get; set; } [Required] public DateTime LastModifiedDate { get; set; } } } |
มีแต่ UserName ยังไม่มี Password
สร้างคลาส Data\ApplicationDbContext.cs
Data\ApplicationDbContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using Microsoft.EntityFrameworkCore; namespace WebApi.Data { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Models.ApplicationUser> Users { get; set; } } } |
บรรทัดที่ 12 : เรียกใช้งานคลาส ApplicationUser
แต่กำหนดชื่อตัวแปรเป็น Users
ก็จะได้ตารางชื่อ dbo.Users
Startup.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 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using WebApi.Data; namespace WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ApplicationDbContext"))); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } } } |
appsettings.json
1 2 3 4 5 6 7 8 9 10 11 |
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "ApplicationDbContext": "Server=(localdb)\\mssqllocaldb;Database=ApplicationDbContext;Trusted_Connection=True;MultipleActiveResultSets=true" } } |
Perform initial migration
[code]
> dotnet ef migrations add Initial
> dotnet ef database update
[/code]
สร้างคลาส 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; 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>>())) { // Create default Users (if there are none) if (!context.Users.Any()) CreateUsers(context); } } private static void CreateUsers(ApplicationDbContext context) { // local variables DateTime createdDate = new DateTime(2016, 03, 01, 12, 30, 00); DateTime lastModifiedDate = DateTime.Now; // Create the "Admin" ApplicationUser account (if it doesn't exist already) var userAdmin = new ApplicationUser() { Id = Guid.NewGuid().ToString(), UserName = "Admin", Email = "admin@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; // Insert the Admin user into the Database context.Users.Add(userAdmin); #if DEBUG // Create some sample registered user accounts (if they don't exist already) var userJack = new ApplicationUser() { Id = Guid.NewGuid().ToString(), UserName = "Jack", Email = "mr.phaisarn@gmail.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; var user_Solice = new ApplicationUser() { Id = Guid.NewGuid().ToString(), UserName = "Solice", Email = "solice@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; var user_Vodan = new ApplicationUser() { Id = Guid.NewGuid().ToString(), UserName = "Vodan", Email = "vodan@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; // Insert sample registered users into the Database context.Users.AddRange(userJack, user_Solice, user_Vodan); #endif context.SaveChanges(); } } } |
บรรทัดที่ 40 : เพิ่มข้อมูลทีละแถว
บรรทัดที่ 72 : เพิ่มข้อมูลทีละหลายๆแถว
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>(); } } |
รันกด F5
เสร็จแล้วกลับมาดูที่ Database จะมีข้อมูลเพิ่มเข้ามา (แต่หน้าเว็บยังไม่เห็นอะไร)