一、引言
一般來講我們做項(xiàng)目都會用實(shí)體類跟數(shù)據(jù)庫實(shí)體進(jìn)行關(guān)系對應(yīng),這樣的好處方便我們維護(hù)、增刪改查,并且可以減少SQL的編寫,從而統(tǒng)一風(fēng)格,那么 Entity Framework Core 就是很不錯的ORM框架。
二、EF Core 的優(yōu)缺點(diǎn)
2.1 優(yōu)點(diǎn):
1、跨數(shù)據(jù)庫支持能力強(qiáng)大,只需修改配置就可以輕松實(shí)現(xiàn)數(shù)據(jù)庫切換。
2、提升了開發(fā)效率,不需要在編寫Sql腳本,但是有些特殊Sql腳本EF無法實(shí)現(xiàn),需要我們自己編寫(通過EF中的ExecuteSqlCommand實(shí)現(xiàn)插入、修改、刪除、SqlQuery執(zhí)行查詢)。
3、EF提供的模型設(shè)計器十分強(qiáng)大,可以讓我們清晰的指定或者查看表與表之間的關(guān)系(一對多,多對多…)。
4、EF提供的導(dǎo)航屬性十分好用。
5、EF的延遲查詢加載機(jī)制,數(shù)據(jù)在用到的時候才會去數(shù)據(jù)庫查詢。
2.2 缺點(diǎn):
1、性能差(生成Sql腳本階段),在復(fù)雜查詢的時候生成的腳本不是很高。
2、第一次執(zhí)行時會有預(yù)熱,預(yù)熱時性能較差,不過將映射關(guān)系加載到內(nèi)存之后就會好很多。
3、對于大批量的數(shù)據(jù)操作效率比較慢。
三、使用前安裝:NuGet包
- Microsoft.EntityFrameworkCore:提供了數(shù)據(jù)上下文和DbSet屬性,我們在程序里面就是通過數(shù)據(jù)上下文和DbSet屬性來對數(shù)據(jù)庫里面的數(shù)據(jù)進(jìn)行操作。
- Micorsoft.EntityFrameworkCore.SqlServer:針對SqlServer數(shù)據(jù)庫的擴(kuò)展,使用SqlServer數(shù)據(jù)庫必須。類似的還有MySql,SqlLite等。
- Micorsoft.EntityFrameworkCore.Tools:執(zhí)行更新腳本。
四、實(shí)體類更新到數(shù)據(jù)庫實(shí)體表
4.1 創(chuàng)建 DBEntity 屬性
作用:因?yàn)槲蚁M莿討B(tài)將實(shí)體類與數(shù)據(jù)庫實(shí)體表關(guān)聯(lián)關(guān)系建立起來,所以我使用屬性特性的方式來實(shí)現(xiàn),只更新同步有此特性的實(shí)體類到數(shù)據(jù)庫實(shí)體表。
文件目錄:放置在Models/Attribute的目錄下。
代碼:
/// <summary>
/// 數(shù)據(jù)庫實(shí)體特性
/// </summary>
public class DBEntityAttribute: Attribute
{
}
4.2 appsettings.json 配置數(shù)據(jù)庫連接串
"ConnectionStrings": {
"DemoContext": "Server=127.0.0.1,1433;DataBase=WebApiDemo;User ID=sa;Password=sa;TrustServerCertificate=true;Trust Server Certificate=true;"
}
4.3 修改 DemoContext 的 OnModelCreating方法、OnConfiguring方法
/// <summary>
/// 創(chuàng)建實(shí)體
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region 動態(tài)加入DbSet<T>屬性
var assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.ExportedTypes)
{
if (type.IsClass && type.GetCustomAttribute<DBEntityAttribute>() != null)
{
var method = modelBuilder.GetType().GetMethods().Where(x => x.Name == "Entity").FirstOrDefault(); //得到當(dāng)前對象的實(shí)體
if (method != null)
{
//加入DbSet<T>屬性
method = method.MakeGenericMethod(new Type[] { type });
method.Invoke(modelBuilder, null);
}
}
}
#endregion
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//base.OnConfiguring(optionsBuilder);
//獲取配置文件對象
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
//注入使用DemoContext連接串
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DemoContext"));
}
4.4 創(chuàng)建實(shí)體類
基礎(chǔ)類:
using System.ComponentModel.DataAnnotations;
namespace ASP.NETCoreApi.Models
{
public class EntityBase
{
/// <summary>
/// 主鍵
/// </summary>
[Key]
public int FID { get; set; }
}
}
注:加入 Key 特性,則會在數(shù)據(jù)庫中自動設(shè)置為自增長主鍵。
實(shí)體類主表:
using System.ComponentModel.DataAnnotations.Schema;
namespace ASP.NETCoreApi.Models
{
[DBEntity]
[Table("T_WDQ_DemoTable")]
public class DemoTable:EntityBase
{
/// <summary>
/// 姓名
/// </summary>
public string FName { get; set; }
/// <summary>
/// 編碼
/// </summary>
public string FNumber { get; set; }
/// <summary>
/// 備注
/// </summary>
public string FRemark { get; set; }
}
}
實(shí)體類子表:
using System.ComponentModel.DataAnnotations.Schema;
namespace ASP.NETCoreApi.Models
{
[DBEntity]
[Table("T_WDQ_DemoTableEntry")]
public class DemoTableEntry: EntryEntityBase
{
public DemoTable DemoTable { get; set; }
/// <summary>
/// 行號
/// </summary>
public int FSeq { get; set; }
/// <summary>
/// 數(shù)量
/// </summary>
public decimal FQty { get; set; }
/// <summary>
/// 單價
/// </summary>
public decimal FPrice { get; set; }
/// <summary>
/// 金額
/// </summary>
public decimal FAmount { get; set; }
}
}
4.5 更新數(shù)據(jù)庫實(shí)體表
需要在程序包管理器控制臺里執(zhí)行同步更新的命令腳本,打開方式:
在執(zhí)行命令前,我們先要了解一下命令的使用,要做到知其然,知其所以然。
- 命令:
Add-Migration [operateName]:添加遷移,每次遷移前必須先執(zhí)行該命令。
[operateName]:操作名,例如:初始化時使用 Initial 命令,新增字段時使用 AddField 命令。
Update-Database:更新數(shù)據(jù)庫,更新新實(shí)體表/字段時執(zhí)行。
script-migration:執(zhí)行該命令后,會根據(jù)最新的遷移文件生成SQL腳本(刪除/修改字段),主要是用于生成SQL腳本后校驗(yàn)要刪除/修改的字段是否正確,校驗(yàn)通過后再到生產(chǎn)環(huán)境中執(zhí)行該SQL腳本。
注:每次只能執(zhí)行一個命令,不允許多個命令同時執(zhí)行。
初始化:
Add-Migration Initial
更新數(shù)據(jù)庫:
Update-Database
五、EF Core 使用增刪改查
具體的使用自行百度吧,這里就不再做闡述了。
六、結(jié)果
文章來源:http://www.zghlxwxcb.cn/news/detail-497597.html
結(jié)語:其實(shí)我是想使用動態(tài)更新實(shí)體對象與數(shù)據(jù)庫實(shí)體表字段的,但是找了很久沒有解決辦法,就逼不得已先手敲命令行的方式來進(jìn)行更新吧。文章來源地址http://www.zghlxwxcb.cn/news/detail-497597.html
到了這里,關(guān)于ASP.NET Core Web API入門之三:使用EF Core的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!