创建一个api,添加引用包
Pomelo.EntityFrameworkCore.MySql
Microsoft.EntityFrameworkCore.Design
创建一个Data文件夹用来存放context,下一级创建一个Entity文件夹用来存放Entity
创建一个UserContext
public class UserContext:DbContext { public UserContext(DbContextOptions<UserContext> options):base(options) { } public DbSet<User> Users { get; set; } }
创建一个Entity
public class User { public int Id { get; set; } public string Name { get; set; } public string Company { get; set; } public string Title { get; set; } }
startup中引入相关配置
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.AddDbContext<UserContext>(options=> { options.UseMySql(Configuration.GetConnectionString("MysqlUser")); }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); InitializeDatabase(app); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } private void InitializeDatabase(IApplicationBuilder app) { using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { var context = serviceScope.ServiceProvider.GetRequiredService<UserContext>(); context.Database.Migrate(); if (!context.Users.Any()) { context.Users.Add(new Data.Entity.User() { Id = 1, Name = "test" }); context.SaveChanges(); } } } }
appsetting中添加配置
"ConnectionStrings": { "MysqlUser": "server=127.0.0.1;port=3306;database=DockerTest;userid=sa2;password=123456" }
执行codefirst命令
Add-Migration init
Update-Database
运行一下程序,查看下数据库