2025年3月31日 星期一 乙巳(蛇)年 正月初一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

10分钟系列:NetCore3.1+EFCore三步快速完成数据库交互

时间:03-16来源:作者:点击数:33

前言

做程序开发,不管是什么语言什么数据库,其中的ORM(对象关系映射)是必不可少的,但是不管选择哪一种ORM,都需要了解其中的运行机制,配置帮助类等等。

所以很多ORM都开始进行升级封装,我们只需要引用即可,可谓是开箱即用,特别是对于初学者来说,快速建站不是梦。

PS:知其然而不知其所以然是不行的,要理解其中的运行机制和原理,不要为了写代码而写代码。

今天他来了,EFCore (Entity FraFramework Core)

Entity Framework Core (EF Core) 是适用于 .NET 的新式对象数据库映射器。 它支持 LINQ 查询、更改跟踪、更新和架构迁移。

EF Core 通过数据库提供程序插件模型与 SQL Server/Azure SQL 数据库、SQLite、Azure Cosmos DB、MySQL、PostgreSQL 和更多数据库配合使用。

三步实现数据库交互

1、创建项目

创建一个ASP .Net Core Web API项目,命名为EFCore_NetCoreWebApi(自定义命名,你可以起一个合适的名字),版本选择Net Core 3.1,

数据库是SqlServer,当然,其他数据库也是可以的,不影响操作,很方便。

2、引入NuGet包并创建上下文对象

这里只需要两个包,一个是EFCore的引用包,一个是数据库连接的引用包。

在NuGet分别引入下面两个包,

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

创建上下文对象

在项目里面创建一个EntityDbContext文件夹,然后在文件夹里面创建一个DbContext_first类,并继承 EFCore框架中的 DbContext,

在EntityDbContext文件夹下创建Entity文件夹,创建StudentTable实体映射。如下展示

PS:(注意,这里默认是数据库存在StudentTable表的,如果没有请先创建,EFCore支持实体映射表到数据库的,这里就不体现了,有需要了解的自行百度或私信小编)

  • using EFCore_NetCoreWebApi.EntityDbContext.Entity;
  • using Microsoft.EntityFrameworkCore;
  • using System;
  • using System.Collections.Generic;
  • using System.Linq;
  • using System.Threading.Tasks;
  • namespace EFCore_NetCoreWebApi.EntityDbContext
  • {
  • public class DbContext_first: DbContext
  • {
  • /// <summary>
  • /// 在这里重写OnConfiguring的方法来配置数据库的连接字符串
  • /// </summary>
  • /// <param name="optionsBuilder"></param>
  • protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  • {
  • //SQL Server/Azure SQL 数据库、SQLite、Azure Cosmos DB、MySQL、PostgreSQL数据库连接
  • optionsBuilder.UseSqlServer("Data Source=DESKTOP-Q1V1K53\\MSSQLSERVER2012; Initial Catalog=Demo;User Id=sa;Password=0000@CIICSH");
  • }
  • public DbSet<StudentTable> StudentTable{ get; set; } //需要操作的数据库对应的表
  • }
  • }

为了很好的展示,配置连接我写在代码里,后续可放到配置文件,注意,NetCore3.1的配置文件读取方式和以往不同,注意甄别,如下,需要查看的点击代码,不需要的可以跳过。

  • 1、首先在控制器引入读配置文件对象
  • private readonly IConfiguration _IConfiguration;
  • public ThirdController(IConfiguration IConfiguration)
  • {
  • _IConfiguration = IConfiguration;
  • }
  • 2、然后读取
  • var AllowedHosts = this._IConfiguration["AllowedHosts"];
  • var write = this._IConfiguration["ConnectionStrings:DbWrite"];
  • var write0 = this._IConfiguration["ConnectionStrings:DbWrite:0"];
  • var readarray = this._IConfiguration.GetSection("ConnectionStrings").GetSection("DbReads").GetChildren().Select(a => a.Value).ToArray();
  • 3、配置文件的格式(看需求配置)
  • {
  • "Logging": {
  • "LogLevel": {
  • "Default": "Information",
  • "Microsoft": "Warning",
  • "Microsoft.Hosting.Lifetime": "Information"
  • }
  • },
  • "ConnectionStrings": {
  • "DbWrite": "Server=.;Database=LhHt6;Persist Security Info=True;User ID=sa;password=Sasa123;MultipleActiveResultSets=true",
  • "DbReads": [
  • "Server=.;Database=LhHt6;Persist Security Info=True;User ID=sa;password=Sasa123;MultipleActiveResultSets=true",
  • "Server=.;Database=LhHt6;Persist Security Info=True;User ID=sa;password=Sasa123;MultipleActiveResultSets=true",
  • "Server=.;Database=LhHt6;Persist Security Info=True;User ID=sa;password=Sasa123;MultipleActiveResultSets=true"
  • ]
  • },
  • "AllowedHosts": "*"
  • }

展示一下创建好后的目录层级

3、编写几行代码

在Controllers文件夹下创建一个StudentController控制器,并配置路由,编写代码,如下:

  • using EFCore_NetCoreWebApi.EntityDbContext;
  • using Microsoft.AspNetCore.Mvc;
  • using System;
  • using System.Collections.Generic;
  • using System.Linq;
  • using System.Threading.Tasks;
  • namespace EFCore_NetCoreWebApi.Controllers
  • {
  • [Route("api/[controller]")]
  • [ApiController]
  • public class StudentController : Controller
  • {
  • //查询
  • [HttpGet("GetStudentList")]
  • public JsonResult GetStudentList()
  • {
  • using (var ctx=new DbContext_first())
  • {
  • var studeltList = ctx.StudentTable.ToList();
  • return Json(studeltList);
  • }
  • }
  • }
  • }

然后我们访问http://localhost:44571/api/Student/GetStudentList就查询到数据了,成功交互,调试查看一下。

到这里就完成了数据库交互了,是不是超少的代码,超简单的逻辑。其他的增删改一样的,我们展示一下新增的例子,修改删除的就不展示了,需要具体了解的可以私信或评论区留言。

  • //增加
  • [HttpGet("StudentInsert")]
  • public string StudentInsert()
  • {
  • using (var ctx = new DbContext_first())
  • {
  • int count = 0;
  • List<StudentTable> modelList = new List<StudentTable>();
  • StudentTable model = new StudentTable();
  • model.Name = "喜洋洋";
  • model.Sex = "男";
  • model.Age = 10;
  • model.ClassName = "发明三班";
  • model.CreateTime = DateTime.Now;
  • ctx.Add(model); //单个添加
  • count = ctx.SaveChanges(); //提交数据库交互
  • //modelList.Add(model);
  • //ctx.AddRange(model); //批量添加
  • //count = ctx.SaveChanges(); //提交数据库交互
  • return count > 0 ? "添加成功" : "添加失败";
  • }
  • }

总结

对接进来很简单,使用也很方便,但是对于复杂sql语句(跨服务器跨库多表的查询)或其他业务场景不满足怎么办?

这个时候就会考虑使用sql语句的方式会不会比较好,调用存储过程是不是更优?在不引入第三方的情况下可以使用ado.net的方式来进行补位,比如:

  •        //sql连接
  • string connectionString = "Data Source=DESKTOP-Q1V1K53\\MSSQLSERVER2012; Initial Catalog=Demo;User Id=sa;Password=0000@CIICSH"using (SqlConnection conn = new SqlConnection(connectionString))
  • {
  • conn.Open();
  • string sql = "";
  • sql = "INSERT INTO StudentTable VALUES('灰太狼','男','20','发明三班',GETDATE())";
  • using (SqlCommand cmd = new SqlCommand(sql, conn))
  • {
  • cmd.ExecuteNonQuery();
  • }
  • conn.Close();
  • conn.Dispose();
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门