前言
做程式開發,不管是什麼語言什麼資料庫,其中的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();
}
歡迎關注訂閱微信公眾號【熊澤有話說】,更多好玩易學知識等你來取
作者:熊澤-學習中的苦與樂 公眾號:熊澤有話說 出處:https://www.cnblogs.com/xiongze520/p/15049031.html 創作不易,任何人或團體、機構全部轉載或者部分轉載、摘錄,請在文章明顯位置註明作者和原文連結。 |