標籤:entity framework mvc4
ORM作為一種資料庫訪問機制已廣泛地應用於各種項目當中,在.Net開發中,應用比較廣泛的ORM架構大致有下面幾個:
官方支援的有:Linq to SQL,Entity Framework。三方的有:NHibernate。前面介紹過Linq to SQL的應用,這篇介紹一下Entity Framework在Asp.Net MVC4中的應用。
首先用Visual Studio(2012或2013,其它版本需要安裝Asp.Net MVC4)建立一個Asp.Net MVC4的項目,項目建立完成後會發現Entity Framework已經被添加到項目當中並已經寫好了一些基本的方法。首先看項目引用References,會看到EntityFramework程式集,再看根目錄下面的設定檔web.config會看到相關配置項:
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
也就是說對於沒有包含Entity Framework的項目而言,如果想使用Entity Framework只需要上面的步驟就行,添加程式集,然後添加設定檔節點資訊(對於設定檔,怎麼自訂配置節點Section,我會在寫完mvc4後的後續博文中介紹)。上面步驟支援code first方式,但如果想用Entity Framework的可視化操作功能,那麼需要安裝Entity Framework工具。
下面來看看具體應用。
Entity Framework支援兩方面的應用,Code First和Database First。Code First即代碼優先原則,也就是說先建立實體類,再根據實體類建立資料庫。另外一種就是Database First即資料庫優先原則,也就是說根據資料庫來自動建立實體類。
先說第一方面的應用,Code First。
第一步:建立實體類。
直接運行剛建立的項目,會看到帳戶管理功能已經做好了,開啟註冊頁面,註冊一個帳戶完成登陸,所有的功能全部已經包含在了建立的項目中,在註冊和登陸時文字框的驗證功能也已經寫好了,開啟解決方案視窗,點擊功能欄上的“顯示所有檔案”,開啟App_Data檔案夾,會看到有一個mdf的資料庫檔案,右鍵選擇”添加到項目中“,開啟資料庫檔案會看到帳戶管理的所有表, 來看一下是如何?的。
開啟Models檔案夾,開啟檔案AccountModels檔案,會看到UsersContext類,它繼承自DbContext類。DbContext類為Entity Framework的基礎,包括初始化資料庫連接,Database類,DbSet類,實體驗證DbEntityValidationResult, 實體類DbEntityEntry等。
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
UserContext類建立一個建構函式並指定執行父類建構函式:public DbContext(string nameOrConnectionString);
DefaultConnection為連接字串,可以查看設定檔:
<connectionStrings>
<add name="DefaultConnection" connectionString="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" providerName="System.Data.SqlClient" />
</connectionStrings>
如果想自訂資料庫位置,那麼可以修改DefaultConnection字串到指定位置,或修改base("DefaultConnection")的connectionString名稱。
DbSet為建立資料庫表的方法,想要建立的表放在DbContext繼承類內。
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}上面是要建立的表的實體類,屬性Table指定表名,也俗稱註解字,註解字的功能不僅僅針對於實體類,還有專門的屬性方法作用於欄位,[Key]指定表的主鍵,[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]則定義主鍵的產生方式。註解字的另一個作用就是在UI層面對使用者輸入的資料進行驗證,將Model綁定到頁面時,相應的欄位與Html標籤綁定,那麼在欄位上定義的各種規定就會用於驗證使用者的輸入,當然在UI層需要@Html.ValidationSummary(true)的支援,不然註解字會被忽略。這個概念就是Model強型別綁定,也就是Model的意義所在。來看看其它各種註解字,如:public class LocalPasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
根據各屬性名稱可以判斷它們具體用於哪些方面的驗證,這一部分內容會放在Htmlhelper裡面具體講解,包括如何?自訂的屬性功能,即註解字功能。寫到這裡面,我們會想到如何建立資料庫呢?來看看建立資料庫的方法。開啟Filters檔案夾,開啟InitializeSimpleMembershipAttribute類,它繼承自ActionFilterAttribute屬性類,Filter是一類可以自訂的操作,特別是那些需要作用整個項目的操作,會在後續博文介紹。private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}上面為初始化方法,_initializer為初始化資料庫類:private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null); try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
} WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see ", ex);
}
}
}這個類的作用是指定資料庫建立策略,並建立資料庫。Database.SetInitializer<UsersContext>(null); 能夠具體指定資料庫建立策略,有三種方式:1. 如果參數為Null,那麼預設為CreateDatabaseIfNotExists,即如果不存在,那麼建立資料庫。2. DropCreateDatabaseAlways,總是先刪除再重新建立新的資料庫。3. DropCreateDatabaseIfModelChanges, 刪除再建立新的資料庫,如果Model有變化。應用方法為:Database.SetInitializer<UsersContext>(new DropCreateDatabaseIfModelChanges<UsersContext>());
上面這些類是已經存在於MVC4項目中的Membership操作,那麼現在來建立自己的實體類和資料庫表。如果想建立一個全部的資料庫,那麼可以直接繼承DbContext類,並自訂自己的資料庫連接字串。如果保留Membership操作裡面類和表,可以繼承UserContext類。簡單一點,保留所有現有的功能,我只需要繼承UserConext。public class DataGridContext : UsersContext
{
public DbSet<DataListForDemo> DataListForDemo { get; set; }
}
先建立一個自己的Context類和實體表。 [Table("DataListForDemo")]
public class DataListForDemo
{
public int ID { get; set; }
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
public string col5 { get; set; }
[DataType(DataType.Date, ErrorMessage="{0} should be a correct date")]
public DateTime col4 { get; set; }
}
運行項目,開啟資料庫會發現新表已經建立好了。這就是Code First的方法,應用Asp.Net MVC4的資料庫持久化。再來看看如果已經設計好資料庫該怎麼操作?
第二種方式:Database First。
添加新項,選擇Data,選擇ADO.Net Entity Data Model,選擇添加。會看到導航介面,提供兩種選擇:從資料庫產生和空Model。第一種方式會提供一個資料庫連接,並可以選擇需要建立哪些表、視圖、預存程序、函數的實體類。第二種方式則建立一個空的模板。操作方式和Linq to SQL出入不大, 和code first相比,這個可圖形化操作,目錄提供EF 5.0和6.0兩個版本,對於複雜的資料庫而言,這是一個很好的方法,我們可以單獨設計好資料庫,根據需要建立需要的實體類。採用這種方式會在項目中建立一個.edmx尾碼的檔案裡麵包括了建立的實體類、實體SP、Function等,操作上沒有太多區別。
public virtual DbSet<C__MigrationHistory> C__MigrationHistory { get; set; }
public virtual DbSet<DataListForDemo> DataListForDemo { get; set; }
public virtual DbSet<UserProfile> UserProfile { get; set; }
public virtual DbSet<webpages_Membership> webpages_Membership { get; set; }
public virtual DbSet<webpages_OAuthMembership> webpages_OAuthMembership { get; set; }
public virtual DbSet<webpages_Roles> webpages_Roles { get; set; }
public virtual ObjectResult<TestLinqToSQL_Result> TestLinqToSQL()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<TestLinqToSQL_Result>("TestLinqToSQL");
}
可圖形化操作,可自動產生代碼等。
上面就是EF在Asp.Net MVC4裡面應用的兩種不同方式,第一種全部包含在了建立的項目中,第二種則需要自己在已經建立好資料庫的時候下建立。下一篇介紹HTML5, CSS3, JQuery和JQuery UI在mvc4裡面的應用。