Mysql EF Core 快速构建 Web Api
(1)首先创建一个.net core web api web项目;
(2)因为我们使用的是ef连接mysql数据库,通过NuGet安装MySql.Data.EntityFrameworkCore,以来的ef core 也会被安装.
(2)在appsettings.json中添加如下数据库连接字符串.
(2)创建数据库对应的model--AppUser
public class AppUser { public int Id { get; set; } public string CompanyName { get; set; } public string Name { get; set; } }
(3)创建dbcontext
public class UserContext:DbContext { public UserContext(DbContextOptions<UserContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<AppUser>() .ToTable("Users") .HasKey(u => u.Id); base.OnModelCreating(modelBuilder); } public DbSet<AppUser> Users { get; set; } }
(4)在startup.cs中配置数据库连接信息。并插入一条记录。
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // 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(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); InitUserDatabase(app); } public void InitUserDatabase(IApplicationBuilder app) { using (var scope = app.ApplicationServices.CreateScope()) { var userContext = scope.ServiceProvider.GetRequiredService<UserContext>(); if (!userContext.Users.Any()) { userContext.Users.Add(new Models.AppUser { Name = "daniel cui", CompanyName = "bat company" }); userContext.SaveChanges(); } } }
(5)执行Add-Migration init生成Migrations文件夹,执行Update-Database init生成数据库并生成表.
(6)启动程序并想Users表插入一条记录.
但是会产生错误信息。目前还没有完美解决。
作者:tuohaibei
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利.
如果您觉得文章对您有帮助,可以点击文章右下角"推荐".您的鼓励是作者坚持原创和持续写作的最大动力!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?