DotNetCore跨平台~EFCore資料內容的建立方式

來源:互聯網
上載者:User

標籤: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資料內容的建立方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.