本文转载自微信公众号“鹏翔”,作者AZRNG。转载本文请联系鹏翔公众号。开场白本文主要回顾了从项目创建到生成数据到数据库的整个过程(codefirst)。EFCore用作ORM框架。本示例环境:vs2019、net5、mysql创建项目本示例代码是使用vs2019创建的ASP.NETCoreWebAPI项目,可以通过可视化界面创建,也可以通过命令行创建。dotnetnewwebapi-oNet5ByDocker创建实体类,安装并连接到MySQL数据库组件5.0.0"/>添加实体类[Table("user")]publicclassUser{publicUser(){Id=Guid.NewGuid().ToString();}publicUser(stringaccount,stringpassword,stringcreater):this(){Account=account;Password=password;Deleted=false;SetCreater(creater);}[Key][Comment("PrimaryKey")][StringLength(36)][Required]publicstringId{get;privateset;}[Comment("Account")][StringLength(36)][Required]publicstringAccount{get;privateset;}[Comment("Password")][StringLength(36)][Required]publicstringPassword{get;privateset;}[Comment("Balance")][Column(TypeName="decimal(18,2)")][Required]publicdecimalMoney{get;set;}[Comment("是否删除")][Column(TypeName="tinyint(1)")][Required]publicboolDeleted{get;privateset;}[Comment("Creator")][StringLength(20)][Required]publicstringCreator{get;privateset;}[Comment("Creationtime")][Required]publicDateTimeCreateTime{get;privateset;}[Comment("Modifier")][StringLength(20)][Required]publicstringModifyer{get;privateset;}[Comment("修改时间")][必需]publicDateTimeModifyTime{get;privateset;}publicvoidSetCreater(stringname){Creator=name;CreateTime=DateTime.Now;SetModifyer(name);}publicvoidSetModifyer(stringname){Modifyer=name;ModifyTime=DateTime.Now;}}这只是增加实体类类型的一种方法。它可能看起来很乱。也可以通过OnModelCreating实现。详情参见参考文档添加数据库上下文。OpenDbContextpublicclassOpenDbContext:DbContext{publicOpenDbContext(DbContextOptionsoptions):base(options){}publicDbSetUsers{get;set;}}启动注入连接数据库操作varconnection=Configuration["DbConfig:Mysql:ConnectionString"];varmigrationsAssembly=内省Extensions.GetTypeInfo(typeof(Startup)).Assembly.GetName().Name;services.AddDbContext(option=>option.UseMySql(connection,ServerVersion.AutoDetect(connection),x=>{x.UseNewtonsoftJson();x.MigrationsAssembly(migrationsAssembly);}));生成迁移文件引用程序集迁移命令add-migrationInit结果image.png取决于生成的迁移文件是否是你期望的,或者你可以在这一步生成数据库,命令:Update-Databasedataseed添加OpenDbSend类,添加数据种子publicclassOpenDbSend{//////生成数据库和数据种子//////数据库上下文///log///重试次数///publicstaticasyncTaskSeedAsync(OpenDbContextdbContext,ILoggerFactoryloggerFactory,int?retry=0){intretryForAvailability=retry.Value;try{dbContext.Database.Migrate();//如果当前数据库不存在,根据当前模型创建,如果存在,调整数据库匹配当前模型awaitInitializeAsync(dbContext).ConfigureAwait(false);//if(dbContext.Database.EnsureCreated())//如果当前数据库不存在,则根据当前模型创建,如果存在,则忽略//awaitInitializeAsync(dbContext).ConfigureAwait(false);}catch(Exceptionex){if(retryForAvailability<3){retryForAvailability++;varlog=loggerFactory.CreateLogger();log.LogError(ex.Message);awaitSeedAsync(dbContext,loggerFactory,retryForAvailability).ConfigureAwait(false);}}}//////初始化数据/////////<返回>publicstaticasyncTaskInitializeAsync(OpenDbContextcontext){if(!context.Set().Any()){awaitcontext.Set().AddAsync(newUser("azrng","123456","azrng")).ConfigureAwait(false);awaitcontext.Set().AddAsync(newUser("张三","123456","azrng")).ConfigureAwait(false);}awaitcontext.SaveChangesAsync().ConfigureAwait(false);}}在项目启动时调用publicstaticasyncTaskMain(string[]args){varhost=CreateHostBuilder(args).Build();using(varscope=host.Services.CreateScope)e()){varservices=scope.ServiceProvider;varloggerFactory=services.GetRequiredService();var_logger=loggerFactory.CreateLogger();try{varopenContext=services.GetRequiredService();awaitOpenDbSend.SeedAsync(openContext,loggerFactory).ConfigureAwait(false);}catch(Exceptionex){_logger.LogError(ex,$"项目启动错误{ex.Message}");}}awaithost.RunAsync().ConfigureAwait(false);}生成数据库启动项目自动生成数据库image.png表结构如下image.png如果后面数据库字段或结构发生变化,可以重新生成迁移文件,再生成数据库查询数据//////用户界面///publicinterfaceIUserService{stringGetName();//////查询用户信息/////////TaskGetDetailsAsync(stringaccount);}//////用户实现///publicclassUserService:IUserService{privatereadonlyOpenDbContext_dbContext;publicUserService(OpenDbContextdbContext){_dbContext=dbContext;}publicstringGetName(){return"AZRNG";}///publicasyncTaskGetDetailsAsync(stringaccount){returnawait_dbContext.Set().FirstOrDefaultAsync(t=>t.Account==account).ConfigureAwait(false);}}一般建议创建一个指定的返回Model类,然后只查询需要的内容,而不是直接返回实体类controller方法//////查询用户详细信息/////////[HttpGet]publicasyncTask>GetDetailsAsync(stringaccount){returnawait_userService.GetDetailsAsync(account).ConfigureAwait(false);}查询结果{"id":"e8976d0a-6ee9-4e2e-b8d8-1fe6e85b727b","account":"azrng","password":"123456","money":0,"deleted":false,"creator":"azrng","createTime":"2021-05-09T15:48:45.730302","modifyer":"azrng","modifyTime":"2021-05-09T15:48:45.730425"}参考文档实体类型:https://docs.microsoft.com/zh-cn/ef/core/modeling/entity-types?tabs=data-注释实体属性:https://docs.microsoft.com/zh-cn/ef/core/modeling/entity-properties?tabs=data-annotations%2Cwithout-nrt