关于.net:NET-5NET-Core使用EF-Core-5连接MySQL数据库写入读取数据示例教程

1次阅读

共计 4080 个字符,预计需要花费 11 分钟才能阅读完成。

本文首发于《.NET 5/.NET Core 应用 EF Core 5(Entity Framework Core)连贯 MySQL 数据库写入 / 读取数据示例教程》

前言

在.NET Core/.NET 5 的利用程序开发,与其常常搭配的数据库可能是 SQL Server。而将.NET Core/.NET 5 应用程序与 SQL Server 数据库的 ORM 组件有微软官网提供的 EF Core(Entity Framework Core),也有像 SqlSugar 这样的第三方 ORM 组件。EF Core 连贯 SQL Server 数据库微软官网就有比拟具体的应用教程和文档。

本文将为大家分享的是在.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 示例我的项目, 这里取名为MySQLSample

我的项目创立好后,删除其中主动生成的多余的文件,最终的构造如下:

装置依赖包

关上程序包管理工具,装置如下对于 EF Core 的依赖包:

  • Microsoft.EntityFrameworkCore
  • Pomelo.EntityFrameworkCore.MySql (5.0.0-alpha.2)
  • Microsoft.Bcl.AsyncInterfaces

请留神 Pomelo.EntityFrameworkCore.MySql 包的版本,安装包时请开启 蕴含预览,如:

创立实体和数据库上下文

创立实体

创立一个实体Person.cs,并定义一些用于测试的属性,如下:

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;}
    }
}

创立数据库上下文

创立一个数据库上下文MyDbContext.cs,如下:

using Microsoft.EntityFrameworkCore;
using MySQLSample.Models;

namespace MySQLSample
{
    public class MyDbContext : DbContext
    {public DbSet<Person> People { get; set;}

        public MyDbContext(DbContextOptions<MyDbContext> 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`)
);

创立好的空数据表 people 如图:

配置 appsettings.json

将 MySQL 数据连贯字符串配置到 appsettings.json 配置文件中,如下:

{
    "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<MyDbContext>(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();
            });
        }
    }
}

创立一个名为 PeopleController 的控制器,写入如下代码:

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;}

        /// <summary>
        /// 创立
        /// </summary>
        /// <returns></returns>
        [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);
        }

        /// <summary>
        /// 读取指定 Id 的数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetById(int id)
        {using (_dbContext)
            {var list = _dbContext.People.Find(id);
                return Ok(list);
            }
        }

        /// <summary>
        /// 读取所有
        /// </summary>
        /// <returns></returns>
        [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。

正文完
 0