一、什麼是dotnetef
Entity Framework (EF) 是一個 ORM 框架,可以將 .NET 應用程序中的對象映射到關係資料庫中。Entity Framework 的核心是 Object Relational Mapping (ORM)。ORM 是一種編程技術,它將關係資料庫中的數據轉換為方便在應用程序中使用的對象。Entity Framework 是 .NET Framework 的一部分,它提供了一組用於執行 CRUD(Create、Read、Update、Delete)和查詢操作的 API。它充分利用了 .NET 的強類型檢查和代碼靜態分析功能。在使用 Entity Framework 時,不再需要編寫複雜的 SQL 查詢,而是利用強類型化的集合和實體來進行資料庫操作。dotnetef是用.net core進行重構的entity framework版本,也是目前開發的主流版本。
二、為什麼使用dotnetef
使用dotnetef帶來的最大好處是它為開發人員提供了一種基於模型的方法,使其可以將 .NET 代碼完全和底層資料庫操作(例如 SQL 查詢)分離。ASP.NET Core 同樣內置了資料庫訪問支持,但這個 API 的層次結構相對 flatter – 沒有分層的 Repository 和 UnitOfWork 等概念。另外一方面,dotnetef可以幫助應用程序錯誤控制,比如錯誤的SQL語句。也就是說dotnetef提供了一種非常好的抽象層,允許開發人員忽略資料庫架構的細節,以更加高級和更抽象的方式工作。
三、dotnetef的常用功能
1.基本的增刪改查操作
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
}
public class CustomerContext : DbContext
{
public CustomerContext(DbContextOptions options)
: base(options)
{
}
public DbSet Customers { get; set; }
}
public class CustomerController : Controller
{
private readonly CustomerContext _context;
public CustomerController(CustomerContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
return View(await _context.Customers.ToListAsync());
}
}
2.使用LinQ,返回需要的實體
// Find all customers in London using .Where()
var query = _context.Customers.Where(c => c.City == "London");
//query can be further refined before it's turned into
//a List by using more LINQ statements
var londonCustomers = query.ToList();
3.分頁查詢
public async Task<IActionResult> Index(int? pageNumber)
{
var pageSize = 2;
return View(await PaginatedList<Customer>.CreateAsync(_context.Customers.AsNoTracking(),
pageNumber ?? 1, pageSize));
}
4.查詢結果的緩存
public class CustomerController : Controller
{
private readonly IDistributedCache _distributedCache;
private readonly CustomerContext _context;
public CustomerController(CustomerContext context,
IDistributedCache distributedCache)
{
_context = context;
_distributedCache = distributedCache;
}
public async Task<IActionResult> GetById(int id)
{
var customer = await _distributedCache.GetAsync($"customer_{id}");
if (customer == null)
{
var customerEntity = await _context.Customers.FindAsync(id);
if (customerEntity == null)
{
return NotFound();
}
var options = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(15));
await _distributedCache.SetAsync($"customer_{id}",
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(customerEntity)), options);
return View(customerEntity);
}
return View(JsonConvert.DeserializeObject<Customer>(Encoding.UTF8.GetString(customer)));
}
}
四、小結
通過本文閱讀,你可以了解到dotnetef的一些常用功能,以及使用dotnetef的好處,包括分離資料庫操作、幫助錯誤控制、使用LinQ,緩存等操作。使用dotnetef可以大大提高Web應用程序的開發效率和性能,進一步提高Web應用程序的流量,助你的網站的流量翻倍。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/151197.html