โปรเจ็กส์แบบ WebApi นี้ ทำการคอนฟิกค่าเกี่ยวกับดาต้าเบสไว้ที่ Startup.cs
แต่ทำการ Seed ที่ Program.cs
สร้างโปรเจ็กส์แบบ WebApi (ด้วย Vdotnet ef database dropisual 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 Microsoft.AspNetCore.Identity; using System; using System.ComponentModel.DataAnnotations; namespace WebApi.Data.Models { public class ApplicationUser : IdentityUser { 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; } } } |
สร้างคลาส Data\ApplicationDbContext.cs
Data\ApplicationDbContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using WebApi.Data.Models; namespace WebApi.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } //public DbSet<Models.ApplicationUser> Users { get; set; } } } |
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using WebApi.Data; using WebApi.Data.Models; 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"))); // Add ASP.NET Identity support services.AddIdentity<ApplicationUser, IdentityRole>( opts => { opts.Password.RequireDigit = true; opts.Password.RequireLowercase = true; opts.Password.RequireUppercase = true; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequiredLength = 7; }) .AddEntityFrameworkStores<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]
ถ้ามีการทำ Migration แล้วมีปัญหา
จะลบ Database แล้วสร้าง Database ขึ้นใหม่
ให้ลบโฟลเดอร์ Migrations
แล้วใช้คำสั่ง
[code]
> dotnet ef database drop
> dotnet ef migrations add Initial
> dotnet ef database update
[/code]
ตอนนี้จะเห็นดาต้าเบส ตาราง แต่ยังไม่มีข้อมูล
ต่อไปทำการ Seed ข้อมูล
สร้างคลาส 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; 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>>())) { var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>(); // Create default Users (if there are none) if (!context.Users.Any()) CreateUsers(context, roleManager, userManager).GetAwaiter().GetResult(); ; } } private static async Task CreateUsers(ApplicationDbContext context, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager) { // local variables DateTime createdDate = new DateTime(2016, 03, 01, 12, 30, 00); DateTime lastModifiedDate = DateTime.Now; string role_Administrator = "Administrator"; string role_RegisteredUser = "RegisteredUser"; //Create Roles (if they doesn't exist yet) if (!await roleManager.RoleExistsAsync(role_Administrator)) { await roleManager.CreateAsync(new IdentityRole(role_Administrator)); } if (!await roleManager.RoleExistsAsync(role_RegisteredUser)) { await roleManager.CreateAsync(new IdentityRole(role_RegisteredUser)); } // Create the "Admin" ApplicationUser account (if it doesn't exist already) var userAdmin = new ApplicationUser() { SecurityStamp = Guid.NewGuid().ToString(), UserName = "Admin", Email = "admin@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; // Insert "Admin" into the Database and assign the "Administrator" and "RegisteredUser" roles to him. if (await userManager.FindByNameAsync(userAdmin.UserName) == null) { await userManager.CreateAsync(userAdmin, "Pass4Admin"); await userManager.AddToRoleAsync(userAdmin, role_RegisteredUser); await userManager.AddToRoleAsync(userAdmin, role_Administrator); // Remove Lockout and E-Mail confirmation. userAdmin.EmailConfirmed = true; userAdmin.LockoutEnabled = false; } #if DEBUG // Create some sample registered user accounts (if they don't exist already) var userJack = new ApplicationUser() { SecurityStamp = Guid.NewGuid().ToString(), UserName = "Jack", Email = "mr.phaisarn@gmail.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; var user_Solice = new ApplicationUser() { SecurityStamp = Guid.NewGuid().ToString(), UserName = "Solice", Email = "solice@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; var user_Vodan = new ApplicationUser() { SecurityStamp = Guid.NewGuid().ToString(), UserName = "Vodan", Email = "vodan@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; // Insert sample registered users into the Database and also assign the "Registered" role to him. if (await userManager.FindByNameAsync(userJack.UserName) == null) { await userManager.CreateAsync(userJack, "Pass4Ryan"); await userManager.AddToRoleAsync(userJack, role_RegisteredUser); // Remove Lockout and E-Mail confirmation. userJack.EmailConfirmed = true; userJack.LockoutEnabled = false; } if (await userManager.FindByNameAsync(user_Solice.UserName) == null) { await userManager.CreateAsync(user_Solice, "Pass4Solice"); await userManager.AddToRoleAsync(user_Solice, role_RegisteredUser); // Remove Lockout and E-Mail confirmation. user_Solice.EmailConfirmed = true; user_Solice.LockoutEnabled = false; } if (await userManager.FindByNameAsync(user_Vodan.UserName) == null) { await userManager.CreateAsync(user_Vodan, "Pass4Vodan"); await userManager.AddToRoleAsync(user_Vodan, role_RegisteredUser); // Remove Lockout and E-Mail confirmation. user_Vodan.EmailConfirmed = true; user_Vodan.LockoutEnabled = false; } #endif await context.SaveChangesAsync(); } } } |
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 จะมีข้อมูลเพิ่มเข้ามา (แต่หน้าเว็บยังไม่เห็นอะไร)