zoukankan      html  css  js  c++  java
  • 10分钟系列:NetCore3.1+EFCore三步快速完成数据库交互

    前言

    做程序开发,不管是什么语言什么数据库,其中的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": "*"
      }
    View Code

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

    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(); }
     
    欢迎关注订阅微信公众号【熊泽有话说】,更多好玩易学知识等你来取
    作者:熊泽-学习中的苦与乐
    公众号:熊泽有话说
    出处:https://www.cnblogs.com/xiongze520/p/15049031.html
    创作不易,任何人或团体、机构全部转载或者部分转载、摘录,请在文章明显位置注明作者和原文链接。  

     

  • 相关阅读:
    C# 截取窗口图像(包括遮挡窗口,最小化窗口)
    C# 自定义DevExpress中XtraMessageBox的窗口Icon
    C# DevExpress的皮肤,没有在多线程中应用
    DevExpress的RibbonForm在WIN7下标题栏透明,没应用程序设置的Skin
    C# RibbonForm的标题Text显示不完全的解决方法
    C# 使用递归获取文件路径,不获取拒绝访问的文件夹
    socket使用
    KMP模板
    HDU1358(KMP)
    windows环境变量
  • 原文地址:https://www.cnblogs.com/xiongze520/p/15049031.html
Copyright © 2011-2022 走看看