在Code First模式中自動創(chuàng)建Entity模型
之前我在博客文章中介紹過如何使用Code First來創(chuàng)建數(shù)據(jù)庫,通過CodeFirst的方式,可以大幅的減少開發(fā)人員的工作量,比傳統(tǒng)的先創(chuàng)建庫再ORM的方式簡單了不少。但是,很多時候,特別是一些MIS系統(tǒng),我們會涉及到大量的實體類型,類似如下所示:
public class DbContext : System.Data.Entity.DbContext { public DbContext() : base("name=DefaultConnection") { } public DbSet<Pencil> Penlils { get; set; } public DbSet<Pen> Pens { get; set; } public DbSet<Ink> Inks { get; set; } public DbSet<Eraser> Erasers { get; set; } //.... }
在常用的CodeFirst方式下,每增加一種類型就需要在DbContext中增加一個屬性。雖然并不算麻煩,但這種手動維護的方式存在如下兩個問題:
當(dāng)實體類型較多且變更比較頻繁的的時候,靠手動的方式維護實體列表很容易出錯。
有的時候,客戶并不會買整套產(chǎn)品,只需要里面的部分模塊,手動維護的方式不方便模塊的裁剪。
此時,就需要我們來實現(xiàn)動態(tài)創(chuàng)建實體模型了,Entity Framework中本身是支持動態(tài)創(chuàng)建實體模型的,上面的實體模型就可以通過如下方式動態(tài)創(chuàng)建:
public class DbContext : System.Data.Entity.DbContext { public DbContext() : base("name=DefaultConnection") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Pencil>(); modelBuilder.Entity<Pen>(); modelBuilder.Entity<Ink>(); modelBuilder.Entity<Eraser>(); //.... } }
PS:修改成這樣的方式后,原來的代碼可能出現(xiàn)如下問題:DbContext中沒有 Inks屬性了。此時只需要將原來的對db.Inks的訪問換成 db.Set<Ink>即可
結(jié)果上述操作后,雖然我們實現(xiàn)了動態(tài)創(chuàng)建,但實體類型還是手動添加的。因此我們還缺少一種實體類型的發(fā)現(xiàn)機制,這種發(fā)現(xiàn)機制在.net中實現(xiàn)還是比較簡單的,這里我采用的是Attribute的方式。
首先寫一個Attribute,
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class PersistentAttribute : Attribute { }
然后將需要自動創(chuàng)建的實體用該Attribute標(biāo)記,
[Persistent] public class Pen [Persistent] public class Ink
最后,根據(jù)標(biāo)記的實體添加實體模型。
public class DbContext : System.Data.Entity.DbContext { public DbContext() : base("name=DefaultConnection") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); var assembly = this.GetType().Assembly; var entityTypes = from type in assembly.GetTypes() where type.GetCustomAttribute<PersistentAttribute>() != null select type; var entityMethod = typeof(DbModelBuilder).GetMethod("Entity"); foreach (var type in entityTypes) { entityMethod.MakeGenericMethod(type).Invoke(modelBuilder, new object[] { }); } } }
通過上述方法,就可以實現(xiàn)實體模型的自動創(chuàng)建了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Asp.Net平臺下的圖片在線裁剪功能的實現(xiàn)代碼(源碼打包)
最近項目中有個圖片在線裁剪功能,本人查找資料,方法如下:前臺展現(xiàn)用jquery.Jcrop實現(xiàn),后臺使用 System.Drawing.Image類來進行裁剪2011-10-10讓Silverlight 2.0動畫動起來Making Silverlight 2.0 animation Start(
Microsoft Expression Blend 2 制作動畫個人感覺倒像3DMAX 可以自動捕捉關(guān)鍵幀2008-11-11.net Core連接MongoDB數(shù)據(jù)庫的步驟詳解
這篇文章主要給大家介紹了關(guān)于.net Core連接MongoDB數(shù)據(jù)庫步驟的相關(guān)資料,文中將實現(xiàn)的步驟一步步介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-02-02ASP.NET?Core使用MiniProfiler分析應(yīng)用
這篇文章介紹了ASP.NET?Core使用MiniProfiler分析應(yīng)用的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02