前一篇文章介紹了應用LLBL Gen生成Entity Framework所需要的類型定義,用一行代碼完成數據資料的讀取,
《LLBL Gen + Entity Framework 程序設計入門》。如果已經對Entity Framework產生興趣,則可以借助於這一篇,來學習Entity Framework如何對資料庫進行操作。
連接字符串的寫法 Database Connection String
string con ="name = ConnectionString.SQL Server (SqlClient)" ;
其中的”ConnectionString.SQL Server (SqlClient)”是配置文件中的連接字符串名稱,App.config的文件內容如下
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <!-- please adjust the connection string embedded in the element below to target the proper catalog / server using the proper user / password combination --> <add name="ConnectionString.SQL Server (SqlClient)" connectionString="metadata=res://*/Entity35.csdl|res://*/Entity35.ssdl|res://*/Entity35.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=Framework;integrated security=SSPI;persist security info=False;packet size=4096"" providerName="System.Data.EntityClient" /> </connectionStrings> </configuration>
或者直接在代碼中嵌入上面的連接字符串的值
string conn="ConnectionString.SQL Server (SqlClient)" connectionString="metadata=res://*/Entity35.csdl|res://*/Entity35.ssdl|res://*/Entity35.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=Framework;integrated security=SSPI;persist security info=False;packet size=4096"" providerName="System.Data.EntityClient";
如果擔心字符串的方法會報錯或是需要動態建立連接字符串,可以構造EntityConnectionStringBuilder類型來生成連接字符串。
// Specify the provider name, server and database. string providerName = "System.Data.SqlClient"; string serverName = "."; string databaseName = "AdventureWorks"; // Initialize the connection string builder for the underlying provider. SqlConnectionStringBuilder sqlBuilder =new SqlConnectionStringBuilder(); // Set the properties for the data source. sqlBuilder.DataSource = serverName; sqlBuilder.InitialCatalog = databaseName; sqlBuilder.IntegratedSecurity = true; // Build the SqlConnection connection string. string providerString = sqlBuilder.ToString(); // Initialize the EntityConnectionStringBuilder. EntityConnectionStringBuilder entityBuilder =new EntityConnectionStringBuilder(); //Set the provider name. entityBuilder.Provider = providerName; // Set the provider-specific connection string. entityBuilder.ProviderConnectionString = providerString; // Set the Metadata location. entityBuilder.Metadata = @"res://*/AdventureWorksModel.csdl| res://*/AdventureWorksModel.ssdl| res://*/AdventureWorksModel.msl"; Console.WriteLine(entityBuilder.ToString());
創建新數據 Create Record
創建一筆新的配置項數據,把它保存到數據庫中,有二種方法:AddToX或是AddObject,然后調用SaveChanges
Entity35DataContext dataContext = new Entity35DataContext(); Configuration configuration = new Configuration(); configuration.MasterKey = "James"; configuration.Description = "My Profile"; // save configuration
dataContext.AddToConfigurations(configuration);.
dataContext.SaveChanges();
//save configruation
dataContext.AddObject("Configuration",configuration);
dataContext.SaveChanges();
注意必須輸入的數據庫字段(NOT NULL)必須要有值,否則會拋出數據庫異常。
更新數據 Update Record
Configuration configuration.....
configuration.Description="New Profile";
dataContext.SaveChanges();
在更改實體的映射屬性之后,調用SaveChanges即可將修改后的屬性值保存到數據庫中。
如果要更新的屬性所映射的是數據表的主鍵,不應該直接更新主鍵,這樣會報錯,而應該先刪除,再創建一筆新的記錄。
刪除數據 Delete Record
Configuration configuraion..... dataContext.DeleteObject(configuration);
被刪除的對象configuration,可以是已經讀取了映射的表的實體,也可以沒有映射過值的對象,構造一個新的內存對象,再把它傳給DeleteObject方法。我認為這個方法的內部實現應該只需要去查找這個實體的主鍵,生成相應的SQL語句即可。
事務 Transaction
如果需要對多個對象進行操作,事務支持可以用dataContext的Connection對象,代碼例子如下
Entity35DataContext dataContext = null; System.Data.Common.DbTransaction tran = null; try { dataContext = new Entity35DataContext(); dataContext.Connection.Open(); tran = dataContext.Connection.BeginTransaction(); Configuration cst = dataContext.Configurations.FirstOrDefault(cc => cc.MasterKey == "James"); cst.Description = "China "; dataContext.SaveChanges(); tran.Commit(); } catch (Exception ex) { if (tran != null) tran.Rollback(); throw ex; } finally { if (dataContext != null && dataContext.Connection.State != ConnectionState.Closed) dataContext.Connection.Close(); }
應用Repository 模式 Apply Repository Pattern
將上面的CRUD操作應用Repository模式封裝,以隔離變化。
public interface IConfigurationRepository { // Query Methods IQueryable<Configuration> FindAllConfiguration(); Configuration GetConfiguration(string key); // Insert/Delete void Add(Configuration configuration); void Delete(Configuration configuration); // Persistence void Save(); }
可以考慮借助於Code Smith代碼生成工具,直接生成這個接口模板,它的實現代碼也非常容易。
查詢 Entity Query
Entity Framework有二種方法寫數據查詢,一種是上面展示的Linq to Entity,它是延遲執行的。另一種是Entity SQL。這種寫法維護起來相對復雜一些,不過性能會好一些。比如一個表有100個字段,Linq to Entity會將這100個字段的值會部讀出來,映射到內存對象中,當數據量很大的時候,這種寫法會產生性能瓶頸。有時候,我們也只需要讀取表的若干個字段,而不是全部,所以有必要研究一下Entity SQL的寫法。
對象查詢 VALUES
SELECT VALUE it FROM FrameworkEntities.Configuration as it
這種寫示會讀取數據表的所有字段,然后構造成Configuration對象,it是查詢對象的別名。
帶參數查詢
SELECT VALUE it FROM FrameworkEntities.Configuration as it where it.MasterKey=@MasterKey
聚合函數
SELECT count(1) FROM FrameworkEntities.Configuration
Top查詢
SELECT top(10) it.MasterKey FROM FrameworkEntities.Configuration as it
Row
SELECT VALUES row(it.MasterKey,it.Description) FROM FrameworkEntities.Configuration as it
這種寫法會構造一個匿名類型,只讀取指定的字段值,返回匿名對象。
Key 主鍵
SELECT VALUE key(it) FROM FrameworkEntities.Configuration as it
返回Configuration表的主鍵
