新建一个Asp.net Core 2.0 WebAPI项目。
添加EntityFrameworkCore引用
建立Data,Models文件夹
Models内建立User.cs
namespace User.API.Models { public class User { public int Id { get; set; } public string Name { get; set; } public string Company { get; set; } public string Title { get; set; } } }
Data内建立UserContext.cs,继承自DBContext
namespace User.API.Data { public class UserContext : DbContext { // 传一个构造函数 // base调用构造函数 public UserContext(DbContextOptions<UserContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { // 重写方法,AppUser生成Users modelBuilder.Entity<AppUser>() .ToTable("Users") .HasKey(u => u.Id); base.OnModelCreating(modelBuilder); } public DbSet<AppUser> Users { get; set; } } }
appsettings.json添加连接字符串
{ "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }, "ConnectionStrings": { "mysqlUser": "server=127.0.0.1;port=3006;database=fieer_mysql;userid=fieer;password=password " } }
Startup.cs内添加服务,生成默认数据
namespace User.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { // 添加 services.AddDbContext<UserContext>(options => { options.UseMySQL(Configuration.GetConnectionString("MySqlUser")); }); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); InitUserDatabase(app); } // 添加默认用户 public void InitUserDatabase(IApplicationBuilder applicationBuilder) { // 依赖注入 using (var scope = applicationBuilder.ApplicationServices.CreateScope()) { var userContext = scope.ServiceProvider.GetRequiredService<UserContext>(); if (!userContext.Users.Any()) { userContext.Users.Add(new Models.AppUser { Name = "fieer" }); userContext.SaveChanges(); } } } } }