1. 程式人生 > >Entity Framework Core介紹(1)

Entity Framework Core介紹(1)

介紹

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
宣告:原創部落格請在轉載時保留原文連結或者在文章開頭加上本人部落格地址,如發現錯誤,歡迎批評指正。凡是轉載於本人的文章,不能設定打賞功能,如有特殊需求請與本人聯絡!

微信公眾號:歡迎關注                                                 QQ技術交流群: 歡迎加群