介紹
Entity Framework (EF) Core 是輕量化、可擴充和跨平台版的常用 Entity Framework 資料通路技術。
EF Core 可用作對象關系映射程式 (O/RM),以便于 .NET 開發人員能夠使用 .NET 對象來處理資料庫,這樣就不必經常編寫大部分資料通路代碼了。
EF Core 支援多個資料庫引擎,請參閱
資料庫提供程式了解詳細資訊。
模型
對于 EF Core,使用模型執行資料通路。 模型由實體類和表示資料庫會話的派生上下文構成,用于查詢和儲存資料。 有關詳細資訊,請參閱
建立模型。
可從現有資料庫生成模型,手動編碼模型使之與資料庫相比對,或使用 EF 遷移基于模型建立資料庫(并在模型随時間推移發生更改後進行相應改進)。
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace Intro
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public int Rating { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
查詢
使用語言內建查詢 (LINQ) 從資料庫檢索實體類的執行個體。 有關詳細資訊,請參閱
查詢資料using (var db = new BloggingContext())
{
var blogs = db.Blogs
.Where(b => b.Rating > 3)
.OrderBy(b => b.Url)
.ToList();
}
儲存資料
使用實體類的執行個體在資料庫中建立、删除和修改資料。 有關詳細資訊,請參閱
using (var db = new BloggingContext())
{
var blog = new Blog { Url = "http://sample.com" };
db.Blogs.Add(blog);
db.SaveChanges();
}
後續步驟
有關介紹性教程,請參閱
Entity Framework Core 入門官方文檔:
https://docs.microsoft.com/zh-cn/ef/core/asp.net core 交流群:787464275 歡迎加群交流
如果您認為這篇文章還不錯或者有所收獲,您可以點選右下角的【推薦】按鈕精神支援,因為這種支援是我繼續寫作,分享的最大動力!
作者:
LouieGuo http://www.cnblogs.com/stulzq聲明:原創部落格請在轉載時保留原文連結或者在文章開頭加上本人部落格位址,如發現錯誤,歡迎批評指正。凡是轉載于本人的文章,不能設定打賞功能,如有特殊需求請與本人聯系!
微信公衆号:歡迎關注 QQ技術交流群: 歡迎加群
