1. 程式人生 > >.NETCore使用EntityFrameworkCore連線資料庫生成實體

.NETCore使用EntityFrameworkCore連線資料庫生成實體

EF Core 通過資料庫提供程式外掛模型與 SQL Server/SQL Azure、SQLite、Azure Cosmos DB、MySQL、PostgreSQL 和更多資料庫配合使用。

使用EF Core 的優點

Entity Framework (EF) Core 是輕量化、可擴充套件、開源和跨平臺版的常用 Entity Framework 資料訪問技術。

EF Core 可用作物件關係對映程式 (O/RM),這可以實現以下兩點:

  • 使 .NET 開發人員能夠使用 .NET 物件處理資料庫。
  • 無需再像通常那樣編寫大部分資料訪問程式碼。

在開始使用EF Core的時候我們需要在專案中引用一些包 使用NuGet管理器直接引入即可 包名如下:

 

 

 Micorsoft.EntityFrameworkCore:EF框架的核心包
 Micorsoft.EntityFrameworkCore.SqlServer:針對SqlServer資料庫的擴充套件

 其他包是為了生成實體使用的。

EF Core不支援用於視覺化設計器的DB模型和嚮導來建立類似於EF 6的實體和上下文類。所以我們需要使用命令來生成。

Scaffold-DbContext命令

Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>] 
                    [-DataAnnotations] [-Force] [-Project] [-StartupProject] [<CommonParameters>]

引數說明:

-OutputDir *** 實體檔案所存放的檔案目錄
-ContextDir *** DbContext檔案存放的目錄
-Context *** DbContext檔名
-Schemas *** 需要生成實體資料的資料表所在的模式
-Tables *** 需要生成實體資料的資料表的集合
-DataAnnotations
-UseDatabaseNames 直接使用資料庫中的表名和列名(某些版本不支援)
-Force 強制執行,重寫已經存在的實體檔案

在VS2019NuGet程式包管理器控制檯執行如下命令:

Scaffold-DbContext "Server=.;Database=DBName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

,命令執行成功之後生成如下類  連線字串在Context類裡面

 

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseSqlServer(@"Server=.;Database=CloudCollector;Trusted_Connection=True;");
            }
        }

  

 使用“new”的簡單的 DbContext 初始化

在業務邏輯類裡面使用using new DbContext 來初始化DbContext

 public Cloud Get(int id)
        {
            using (var db = new CloudCollectorContext())
            {
                var result = db.Clouds.Where(t => t.Status == 1&&t.Id==id).FirstOrDefault();
                return result;
            }
        }

ASP.NET Core 依賴關係注入中的 DbContext

在.NetCore中開發要求需要IOC 所以我們需要在MVC的Startup的ConfigureServices方法中註冊DbContext 註冊程式碼如下

 services.AddDbContext<CloudCollectorContext>(
        options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));

appsettings.json檔案配置如下:

"ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=CloudCollector;Trusted_Connection=True;"
  }

如此我們便可以使用依賴注入方式實現DbContext初始化了

public Cloud Get(int id)
        {
            var result=_context.Clouds.Where(t => t.Status == 1 && t.Id == id).FirstOrDefault();
            return result;
        }

 整個EFCore連線資料庫初始化DbContext的方法就這樣完成了。