.NET 5/.NET Core使用EF Core 5连接MySQL数据库写入/读取数据示例教程
时间:2023-01-19
浏览:297
作者:佚名
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《.NET 5/.NET Core使用EF Core 5连接MySQL数据库写入/读取数据示例教程》,聊聊MySQL、.NET、c#、.net-core、ef-core,我们一起来看看吧!
本文首发于《.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据示例教程》
本文将为大家分享的是在.NET Core/.NET 5应用程序中使用EF Core 5连接MySQL数据库的方法和示例。
本示例《.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据示例教程》源码托管地址:
https://gitee.com/codedefault/efcore-my-sqlsample
创建示例项目
使用Visual Studio 2019(当然,如果你喜欢使用VS Code也是没有问题的,笔者还是更喜欢在Visual Studio编辑器中编写.NET代码)创建一个基于.NET 5的Web API示例项目,这里取名为
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MySQLSample.Models
{
[Table("people")]
public class Person
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime CreatedAt { get; set; }
}
}创建数据库上下文
创建一个数据库上下文
using Microsoft.EntityFrameworkCore;
using MySQLSample.Models;
namespace MySQLSample
{
public class MyDbContext : DbContext
{
public DbSet People { get; set; }
public MyDbContext(DbContextOptions options) : base(options)
{
}
}
} 数据表脚本
CREATE TABLE `people` ( `Id` int NOT NULL AUTO_INCREMENT, `FirstName` varchar(50) NULL, `LastName` varchar(50) NULL, `CreatedAt` datetime NULL, PRIMARY KEY (`Id`) );
创建好的空数据表
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MySQL": "server=192.168.1.22;userid=root;password=xxxxxx;database=test;"
}
}
Startup.cs注册
在Startup.cs注册MySQL数据库上下文服务,如下:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MySQLSample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options => options.UseMySql(Configuration.GetConnectionString("MySQL"), MySqlServerVersion.LatestSupportedServerVersion));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
} 创建一个名为
using Microsoft.AspNetCore.Mvc;
using MySQLSample.Models;
using System;
using System.Linq;
namespace MySQLSample.Controllers
{
[ApiController]
[Route("api/[controller]/[action]")]
public class PeopleController : ControllerBase
{
private readonly MyDbContext _dbContext;
public PeopleController(MyDbContext dbContext)
{
_dbContext = dbContext;
}
///
/// 创建
///
///
[HttpGet]
public IActionResult Create()
{
var message = "";
using (_dbContext)
{
var person = new Person
{
FirstName = "Rector",
LastName = "Liu",
CreatedAt = DateTime.Now
};
_dbContext.People.Add(person);
var i = _dbContext.SaveChanges();
message = i > 0 ? "数据写入成功" : "数据写入失败";
}
return Ok(message);
}
///
/// 读取指定Id的数据
///
///
[HttpGet]
public IActionResult GetById(int id)
{
using (_dbContext)
{
var list = _dbContext.People.Find(id);
return Ok(list);
}
}
///
/// 读取所有
///
///
[HttpGet]
public IActionResult GetAll()
{
using (_dbContext)
{
var list = _dbContext.People.ToList();
return Ok(list);
}
}
}
}访问地址:
http://localhost:8166/api/people/create来向MySQL数据库写入测试数据,返回结果为:

查看MySQL数据库
people表的结果:

说明使用EF Core 5成功连接到MySQL数据并写入了期望的数据。
再访问地址:
http://localhost:8166/api/people/getall查看使用EF Core 5读取MySQL数据库操作是否成功,结果如下:

到此,.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据的示例就大功告成了。
谢谢你的阅读,希望本文的.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据的示例对你有所帮助。
我是码友网的创建者-Rector。
好了,本文到此结束,带大家了解了《.NET 5/.NET Core使用EF Core 5连接MySQL数据库写入/读取数据示例教程》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多数据库知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
