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
創作不易,任何人或團體、機構全部轉載或者部分轉載、摘錄,請在文章明顯位置注明作者和原文鏈接。  

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM