?
微軟企業庫 Enterprise Library 5.0 正式發布!!!
Enterprise Library 5.0 開發向導- 簡介(1)
Enterprise Library v5.0 -- Data Access Application Block 開發向導(2)
檢索數據對象
現代程序開發都關注“數據對象”,使用數據傳輸對象(DTO)在應用程序層間傳遞數據,使用ORM(Object/Relations Mapping)實現數據訪問層,或者充分利用客戶端數據訪問技術,如LINQ等等。
DAAB提供了使用SQL語句或存儲過程檢索數據的功能,返回的數據實現了IEnumerable接口的對象序列。
關于Accessors
DAAB數據訪問塊提供了2個核心類來執行這一查詢:SprocAccessor和SqlStringAccessor。你可以使用Database 類的ExecuteSprocAccessor和ExecuteSqlStringAccessor方法,在一個方法中創建和執行這些Accessors。
Accessors使用2個其他的對象來管理你想傳遞給accessor的參數,并將從數據庫返回的數據行映射為對象屬性,然后返回給客戶端代碼。下圖演示了整個流程。
如果你不指定參數mapper,accessor將自動使用默認的mapper來解析參數,但是這一特性僅僅適用于SQL Server或Oracle數據庫的存儲過程。當你使用SQL語句或者其他數據庫時,你必須知道定制的參數mapper,負責解析參數。
如果你只指定輸出的mapper,DAAB將使用默認的映射構造類,映射返回的數據列到創建的對象屬性。此外,你也可以創建定制的映射,匹配數據列和對象屬性。
創建并執行Accessor
下面的代碼演示如何使用accessor執行一個存儲過程,并操作返回的對象序列。你必須指定返回數據的對象類型。在本示例中是一個簡單的Product類,有三個屬性:ID、Name和Description。
// Create an object array and populate it with the required parameter values
object[] params = new object[] { "%bike%" };
// Create and execute a sproc accessor that uses the default
// parameter and output mappings.
var productData = defaultDB. ExecuteSprocAccessor <Product>("GetProductList",
params);
// Perform a client‐side query on the returned data. Be aware that
// the orderby and filtering is happening on the client, not in the database.
var results = from productItem in productData
where productItem.Description != null
orderby productItem.Name
select new { productItem.Name, productItem.Description };
// Display the results
foreach (var item in results)
{
Console.WriteLine("Product Name: {0}", item.Name);
Console.WriteLine("Description: {0}", item.Description);
Console.WriteLine();
}
使用LINQ訪問Accessor返回的數據序列,刪除description為空的數據,并按name排序,接著創建一個新的對象序列,包括Name和Description屬性。
檢索XML 數據
幾年前,XML是非常酷的新技術,將掌管未來世界和改變我們思考數據的方法。在很多情況下,從關系型數據庫中檢索XML數據是非常有用的,DAAB支持這一功能。
DAAB提供了檢索XML數據的ExecuteXmlReader方法,接收包含FOR XML的SQL語句,向數據庫執行SQL語句,返回結果為XmlReader。你可遍歷返回的XML元素或使用.NET 框架支持的XML類。然而,SQLXML僅限于Microsoft SQL Server數據庫。
static SqlDatabase sqlServerDB = null;
// Resolve a SqlDatabase object from the container using the default database.
sqlServerDB = EnterpriseLibraryContainer.Current.GetInstance<Database>() as SqlDatabase;
// Specify a SQL query that returns XML data
string xmlQuery = "SELECT * FROM OrderList WHERE State = @state FOR XML AUTO";
// Create a suitable command type and add the required parameter
// NB: ExecuteXmlReader is only available for SQL Server databases
using (DbCommand xmlCmd = sqlServerDB.GetSqlStringCommand(xmlQuery))
{
xmlCmd.Parameters.Add(new SqlParameter("state", "Colorado"));
using (XmlReader reader = sqlServerDB.ExecuteXmlReader(xmlCmd))
{
while (!reader.EOF) // Iterate through the elements in the XmlReader
{
if (reader.IsStartElement())
{
Console.WriteLine(reader.ReadOuterXml());
}
}
}
}
上述代碼演示了使用ExecuteXmlReader方法,從XmlReader檢索返回的XML數據。需要注意的是,默認情況下,返回結果為XML數據塊,并不是一個有效的XML文檔。
使用上述代碼查詢SQL Server數據庫,按FOR XML AUTO查詢,返回默認格式的XML數據,數據集中每一列表示為XML屬性,如下所示。
<OrderList Id="1" Status="DRAFT" CreatedOn="2009‐02‐01T11:12:06" Name="Adjustable
Race" LastName="Abbas" FirstName="Syed" ShipStreet="123 Elm Street" ShipCity="Denver"
ShipZipCode="12345" ShippingOption="Two‐day shipping" State="Colorado" />
<OrderList Id="2" Status="DRAFT" CreatedOn="2009‐02‐03T01:12:06" Name="All‐Purpose
Bike Stand" LastName="Abel" FirstName="Catherine" ShipStreet="321 Cedar Court"
ShipCity="Denver" ShipZipCode="12345" ShippingOption="One‐day shipping"
State="Colorado" />
檢索單一結果
訪問數據的一個常見需求是檢索一個單一數據值。DAAB提供了ExecuteScalar方法實現這一需求。它執行了指定的查詢,并以Object類型返回第一行/第一列的數值。這意味著,它比ExecuteReader方法提供更好的性能,因為不必創建DataReader對象和構造結果集返回給客戶端。為了最大化效率,你應該使用查詢返回一個單一值,或者單一行。
// Create a suitable command type for a SQL statement
// NB: For efficiency, aim to return only a single value or a single row.
using (DbCommand sqlCmd
= defaultDB.GetSqlStringCommand("SELECT [Name] FROM States"))
{
// Call the ExecuteScalar method of the command
Console.WriteLine("Result using a SQL statement: {0}",
defaultDB.ExecuteScalar(sqlCmd).ToString());
}
// Create a suitable command type for a stored procedure
// NB: For efficiency, aim to return only a single value or a single row.
using (DbCommand sprocCmd = defaultDB.GetStoredProcCommand("GetStatesList"))
{
// Call the ExecuteScalar method of the command
Console.WriteLine("Result using a stored procedure: {0}",
defaultDB.ExecuteScalar(sprocCmd).ToString());
}
更新數據
當使用UPDATE、DELETE、或者INSERT 語句時,可調用Database類的ExecuteNonQuery方法,執行數據更新操作。
和前面介紹的ExecuteReader方法一樣,ExecuteNonQuery方法有一系列重載。你可以指定CommandType(默認為StoredProcedure)和SQL語句、存儲過程的名稱等等。你可傳遞對象實例數組,表示查詢參數。此外,你也可傳遞Command對象,包含了你需要的任何參數,同時也提供了Begin和End版本的方法,用來異步執行更新操作。
string oldDescription = "Carries 4 bikes securely; steel construction, fits 2\" receiver hitch.";
string newDescription = "Bikes tend to fall off after a few miles.";
// Create command to execute the stored procedure and add the parameters.
DbCommand cmd = defaultDB.GetStoredProcCommand("UpdateProductsTable");
defaultDB.AddInParameter(cmd, "productID", DbType.Int32, 84);
defaultDB.AddInParameter(cmd, "description", DbType.String, newDescription);
// Execute the query and check if one row was updated.
if (defaultDB.ExecuteNonQuery(cmd) == 1)
{
// Update succeeded.
}
else
{
Console.WriteLine("ERROR: Could not update just one row.");
}
// Change the value of the second parameter
defaultDB.SetParameterValue(cmd, "description", oldDescription);
// Execute query and check if one row was updated
if (defaultDB.ExecuteNonQuery(cmd) == 1)
{
// Update succeeded.
}
else
{
Console.WriteLine("ERROR: Could not update just one row.");
}
操作DataSet 數據集
DAAB支持檢索DataSet數據集,同時也支持從DataSet更新原始的數據庫記錄。
你可以是ExecuteDataSet方法,獲取一個新的DataSet對象實例,該DataSet對象包含有查詢返回的數據表。DataSet中的數據表有默認的表名稱,如Table、Table1和Table2等等。
如果你想將數據裝載進一個現存的DataSet對象,你可以使用LoadDataSet方法,這樣允許你指定名稱或DataSet中的目標數據表,還可讓你添加額外的數據表到一個現有的DataSet,或者更新DataSet中的特定表的內容。
DataSet productDataSet;
// Using a SQL statement and a parameter array.
productDataSet = db.ExecuteDataSet(CommandType.Text, "GetProductsByCategory",
new Object[] { "%bike%" });
// Using a stored procedure and a parameter array.
productDataSet = db.ExecuteDataSet("GetProductsByCategory",
new Object[] { "%bike%" });
// Using a stored procedure and a named parameter.
DbCommand cmd = db.GetStoredProcCommand("GetProductsByCategory");
db.AddInParameter(cmd, "CategoryID", DbType.Int32, 7);
productDataSet = db.ExecuteDataSet(cmd);
Enterprise Library v5.0 -- Data Access Application Block 開發向導(3)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
