標籤:protect ssl 通過 set nconf ddb word mysql use
回到目錄
對於DotNetCore來說,把大部分組件者放在DI容器裡,在startup中進行注入,在類的構造方法中進行使用,如果某些情況下,無法使用這種DI的方式,也可以自己控制資料內容的生產過程,下面說一下。
一 標準注入+構造方法使用
資料內容的定義,帶參數的構造方法,注意他和使用什麼類型的資料庫沒有關係,只是單純的上下文
public partial class ErpContext : DbContext, IERPContext { public ErpContext(DbContextOptions dbContextOptions) : base(dbContextOptions) { } }
startup類中去注入指定的資料來源和資料庫連接串,注意在這裡就有了資料庫類型(如sqlserver,mysql,sqllite)和資料連線串
services.AddDbContextPool<ErpContext>( options => options.UseMySql("Server=123.56.31.133;DataBase=erp;UID=front;Password=PlP2017_#Test;charset=utf8;port=3306;SslMode=None"));
而對於使用者來說,就是某個控制器上,也是通過構造方法的DI來實現的,事實上dotnetcore把ioc&di這些模式都整合了
public ValuesController(ErpContext context) { this.context = context; }
二 不使用注入,直接建立資料內容,手動建立DbContextOptions對象
這種類似於傳統的方法,資料內容對象裡固定串連串,即某個上下文只屬於某個資料庫!
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql("Server=123.56.31.133;DataBase=erp;UID=front;Password=PlP2017_#Test;charset=utf8;port=3306;SslMode=None"); base.OnConfiguring(optionsBuilder); }
三 還有一種就是,即使用注入,也使用自動構造的方式來建立資料內容
事實上就是在初始化上下文時,把optionsBuilder做為參數傳進來,這個比較靈活
public class ERPRepository<T> : EFRepository<T> where T : class { public ERPRepository() : base(new ErpContext( new DbContextOptionsBuilder().UseMySql("Server=123.56.31.133;DataBase=erp;UID=front;Password=PlP2017_#Test;charset=utf8;port=3306;SslMode=None").Options)) { } }
以上幾種方式就是我們使用資料內容時的方法,還有一點要說話的,當使用了Pomelo.EntityFrameworkCore.MySql
這個包包之後,請觀察一下代碼的效能,主要表現在linq的一對多查詢上,代碼如下:
//一對多,效率很低 var linq2 = from data1 in crm_customers.GetModel() join data2 in crm_customertag.GetModel() on data1.Id equals data2.CustomerId into list select new { name = data1.AccountantName, orders = list, }; var result2 = linq2.Take(10).ToList();
感謝各位的閱讀!
我們下次將對一些效能存在問題的代碼進行改善!
回到目錄
DotNetCore跨平台~EFCore資料內容的建立方式