网站建设毕业设计任务书,logo参考网站,潍城区住房和城乡建设局网站,photoshop画简单网站开篇语本文主要是回顾下从项目创建到生成数据到数据库(代码优先)的全部过程。采用EFCore作为ORM框架。本次示例环境#xff1a;vs2019、net5、mysql创建项目本次事例代码是用过vs2019创建的ASP.NET Core Web API项目可以通过可视化界面创建或者通过命令行创建dotnet new webap… 开篇语本文主要是回顾下从项目创建到生成数据到数据库(代码优先)的全部过程。采用EFCore作为ORM框架。本次示例环境vs2019、net5、mysql创建项目本次事例代码是用过vs2019创建的ASP.NET Core Web API项目可以通过可视化界面创建或者通过命令行创建dotnet new webapi -o Net5ByDocker
创建实体类安装连接MySQL数据库组件 PackageReference IncludePomelo.EntityFrameworkCore.MySql Version5.0.0 /PackageReference IncludePomelo.EntityFrameworkCore.MySql.Json.Newtonsoft Version5.0.0 /
增加实体类 [Table(user)]public class User{public User(){Id Guid.NewGuid().ToString();}public User(string account, string password, string creater) : this(){Account account;Password password;Deleted false;SetCreater(creater);}[Key][Comment(主键)][StringLength(36)][Required]public string Id { get; private set; }[Comment(帐号)][StringLength(36)][Required]public string Account { get; private set; }[Comment(密码)][StringLength(36)][Required]public string Password { get; private set; }[Comment(余额)][Column(TypeName decimal(18, 2))][Required]public decimal Money { get; set; }[Comment(是否删除)][Column(TypeName tinyint(1))][Required]public bool Deleted { get; private set; }[Comment(创建人)][StringLength(20)][Required]public string Creater { get; private set; }[Comment(创建时间)][Required]public DateTime CreateTime { get; private set; }[Comment(修改人)][StringLength(20)][Required]public string Modifyer { get; private set; }[Comment(修改时间)][Required]public DateTime ModifyTime { get; private set; }public void SetCreater(string name){Creater name;CreateTime DateTime.Now;SetModifyer(name);}public void SetModifyer(string name){Modifyer name;ModifyTime DateTime.Now;}}
这种只是增加实体类类型的一种方式可能这种看着比较乱还可以通过OnModelCreating实现详情看参考文档增加数据库上下文OpenDbContext public class OpenDbContext : DbContext{public OpenDbContext(DbContextOptionsOpenDbContext options): base(options){}public DbSetUser Users { get; set; }}
Startup注入连接数据库操作 var connection Configuration[DbConfig:Mysql:ConnectionString];var migrationsAssembly IntrospectionExtensions.GetTypeInfo(typeof(Startup)).Assembly.GetName().Name;services.AddDbContextOpenDbContext(option option.UseMySql(connection, ServerVersion.AutoDetect(connection), x {x.UseNewtonsoftJson();x.MigrationsAssembly(migrationsAssembly);}));
生成迁移文件引用组件PackageReference IncludeMicrosoft.EntityFrameworkCore.Design Version5.0.5
PackageReference IncludeMicrosoft.EntityFrameworkCore.Tools Version5.0.5
迁移命令add-migration Init
结果image.png要看下生成的迁移文件是否是自己预期的那样子也可以在这一步就生成数据库命令Update-Database数据种子增加OpenDbSend类添加数据种子 public class OpenDbSend{/// summary/// 生成数据库以及数据种子/// /summary/// param namedbContext数据库上下文/param/// param nameloggerFactory日志/param/// param nameretry重试次数/param/// returns/returnspublic static async Task SeedAsync(OpenDbContext dbContext,ILoggerFactory loggerFactory,int? retry 0){int retryForAvailability retry.Value;try{dbContext.Database.Migrate();//如果当前数据库不存在按照当前 model 创建如果存在则将数据库调整到和当前 model 匹配await InitializeAsync(dbContext).ConfigureAwait(false);//if (dbContext.Database.EnsureCreated())//如果当前数据库不存在按照当前 model创建如果存在则不管了。// await InitializeAsync(dbContext).ConfigureAwait(false);}catch (Exception ex){if (retryForAvailability 3){retryForAvailability;var log loggerFactory.CreateLoggerOpenDbSend();log.LogError(ex.Message);await SeedAsync(dbContext, loggerFactory, retryForAvailability).ConfigureAwait(false);}}}/// summary/// 初始化数据/// /summary/// param namecontext/param/// returns/returnspublic static async Task InitializeAsync(OpenDbContext context){if (!context.SetUser().Any()){await context.SetUser().AddAsync(new User(azrng, 123456, azrng)).ConfigureAwait(false);await context.SetUser().AddAsync(new User(张三, 123456, azrng)).ConfigureAwait(false);}await context.SaveChangesAsync().ConfigureAwait(false);}}
设置项目启动时候调用 public static async Task Main(string[] args){var host CreateHostBuilder(args).Build();using (var scope host.Services.CreateScope()){var services scope.ServiceProvider;var loggerFactory services.GetRequiredServiceILoggerFactory();var _logger loggerFactory.CreateLoggerProgram();try{var openContext services.GetRequiredServiceOpenDbContext();await OpenDbSend.SeedAsync(openContext, loggerFactory).ConfigureAwait(false);}catch (Exception ex){_logger.LogError(ex, $项目启动出错 {ex.Message});}}await host.RunAsync().ConfigureAwait(false);}
生成数据库启动项目自动生成数据库image.png表结构如下image.png如果后期数据库字段或者结构有变动可以再次生成迁移文件然后生成数据库查询数据 /// summary/// 用户接口/// /summarypublic interface IUserService{string GetName();/// summary/// 查询用户信息/// /summary/// param nameaccount/param/// returns/returnsTaskUser GetDetailsAsync(string account);}/// summary/// 用户实现/// /summarypublic class UserService : IUserService{private readonly OpenDbContext _dbContext;public UserService(OpenDbContext dbContext){_dbContext dbContext;}public string GetName(){return AZRNG;}///inheritdoc crefIUserService.GetDetailsAsync(string)/public async TaskUser GetDetailsAsync(string account){return await _dbContext.SetUser().FirstOrDefaultAsync(t t.Account account).ConfigureAwait(false);}}
一般更推荐建立指定的返回Model类然后只查询需要的内容不直接返回实体类控制器方法 /// summary/// 查询用户详情/// /summary/// param nameaccount/param/// returns/returns[HttpGet]public async TaskActionResultUser GetDetailsAsync(string account){return await _userService.GetDetailsAsync(account).ConfigureAwait(false);}
查询结果{id: e8976d0a-6ee9-4e2e-b8d8-1fe6e85b727b,account: azrng,password: 123456,money: 0,deleted: false,creater: 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?tabsdata-annotations实体属性https://docs.microsoft.com/zh-cn/ef/core/modeling/entity-properties?tabsdata-annotations%2Cwithout-nrt