Entity Framework(實體框架)之EntityClient, ObjectQuery
介紹
以Northwind為示例數據庫,ADO.NET Entity Framework之詳解EntityClient, ObjectQuery
EntityConnection - 與存儲模型的連接
EntityCommand - 對 EDM 執行的命令
EntityParameter - 配置 EntityCommand 的參數
EntityDataReader - 以只讀、只進的數據流的方式獲取數據(內存中始終只有一行)。相當於 SqlDataReader
ObjectQuery<T> - 通過 Entity SQL 或 查詢語法 或 Linq 方法對概念模型做查詢
ObjectContext.CreateQuery<T>(Entity SQL) - 根據 esql 創建一個 ObjectQuery<T> 。(延遲)
示例
1、關於EntityClient
EntityClient.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.Objects; using System.Data.Objects.DataClasses; using System.Data.EntityClient; using System.Data; using VS2008SP1.Business; public partial class EntityFramework_EntityClient : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Demo(); result.InnerHtml += "<br />"; Demo2(); result.InnerHtml += "<br />"; Demo3(); } } void Demo() { string strConn = System.Configuration.ConfigurationManager.ConnectionStrings ["NorthwindEntities"].ConnectionString; // EntityConnection - 與存儲模型的連接。構造函數的參數為連接字符串 // Open() - 打開連接 // Close() - 關閉連接 // CreateCommand() - 創建此連接的 EntityCommand 對象 using (EntityConnection conn = new EntityConnection(strConn)) { conn.Open(); try { // EntityCommand - 對 EDM 執行的命令 // CommandType - 命令類型 [System.Data.CommandType枚舉] // CommandType.Text - esql語句。默認值 // CommandType.StoredProcedure - 存儲過程名 // CommandType.TableDirect - 表名 // CommandText - 命令文本。esql語句或存儲過程名或表名 // CommandTimeout - 超時時間。單位:秒 using (EntityCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "select value c from NorthwindEntities.Categories as c"; // EntityDataReader - 以只讀、只進的數據流的方式獲取數據(內存中始終只有 一行)。相當於SqlDataReader // Read() - 讀下一條記錄 // HasRows() - 是否還有可讀數據 // Close() - 關閉 EntityDataReader // EntityCommand.ExecuteReader() - 執行命令,返回 EntityDataReader 對象 using (EntityDataReader edr = cmd.ExecuteReader (CommandBehavior.SequentialAccess)) { while (edr.Read()) { result.InnerHtml += edr["CategoryName"].ToString() + "<br />"; } } } } catch (Exception ex) { result.InnerHtml += ex.ToString(); } finally { conn.Close(); } } /**//* SELECT [Extent1].[CategoryID] AS [CategoryID], [Extent1].[CategoryName] AS [CategoryName], [Extent1].[Description] AS [Description], [Extent1].[Picture] AS [Picture] FROM [dbo].[Categories] AS [Extent1] */ } void Demo2() { // EntityConnection 構造函數的參數為 name = web.config中的connectionStrings中配置的 連接字符串的name using (EntityConnection conn = new EntityConnection("name = NorthwindEntities")) { conn.Open(); try { using (EntityCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "select value s from NorthwindEntities.categories as s where s.categoryId = @categoryId"; // EntityParameter - 配置 EntityCommand 的參數 // ParameterName - 參數名 // Value- 參數值 // Size - 參數大小 // DbTyp - 參數類型 [System.Data.DbType 枚舉] // IsNullable - 是否接受 null 值 EntityParameter param = new EntityParameter(); param.ParameterName = "categoryId"; param.Value = 1; // EntityCommand.Parameters.Add() - 為 EntityCommand 增加參數 cmd.Parameters.Add(param); using (EntityDataReader edr = cmd.ExecuteReader (CommandBehavior.SequentialAccess)) { while (edr.Read()) { result.InnerHtml += edr.GetString(1) + "<br />"; } } } } catch (Exception ex) { result.InnerHtml += ex.ToString(); } finally { conn.Close(); } } /**//* exec sp_executesql N'SELECT [Extent1].[CategoryID] AS [CategoryID], [Extent1].[CategoryName] AS [CategoryName], [Extent1].[Description] AS [Description], [Extent1].[Picture] AS [Picture] FROM [dbo].[Categories] AS [Extent1] WHERE [Extent1].[CategoryID] = @categoryId',N'@categoryId int',@categoryId=1 */ } void Demo3() { // EntityConnectionStringBuilder - 構造連接字符串 EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(); entityBuilder.Provider = "System.Data.SqlClient"; entityBuilder.ProviderConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"; entityBuilder.Metadata = @"res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl"; using (EntityConnection conn = new EntityConnection(entityBuilder.ConnectionString)) { conn.Open(); try { using (EntityCommand cmd = conn.CreateCommand()) { // 調用存儲過程(需要先做好映射,然後指定概念模型中的函數名稱) cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "NorthwindEntities.GetCategory"; EntityParameter param = new EntityParameter(); param.ParameterName = "CategoryID"; param.Value = 1; cmd.Parameters.Add(param); using (EntityDataReader edr = cmd.ExecuteReader (CommandBehavior.SequentialAccess)) { while (edr.Read()) { result.InnerHtml += edr["CategoryName"].ToString() + "<br />"; } } } } catch (Exception ex) { result.InnerHtml += ex.ToString(); } finally { conn.Close(); } } /**//* exec [dbo].[spSelectCategory] @CategoryID=1 */ } }
2、關於ObjectQuery
ObjectQuery.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.Objects; using System.Data.Objects.DataClasses; using System.Data.EntityClient; using System.Data; using System.Data.Common; using VS2008SP1.Business; public partial class EntityFramework_ObjectQuery : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Demo(); result.InnerHtml += "<br />"; Demo2(); result.InnerHtml += "<br />"; Demo3(); result.InnerHtml += "<br />"; Demo4(); } } private void Demo() { using (var ctx = new NorthwindEntities()) { string esql = "select value c from NorthwindEntities.Categories as c"; // ObjectQuery<T> - 通過 Entity SQL 或 查詢語法 或 Linq 方法對概念模型做查 詢 // ObjectContext.CreateQuery<T>(Entity SQL) - 根據 esql 創建一個 ObjectQuery<T> 。(延遲) ObjectQuery<Categories> query = ctx.CreateQuery<Categories>(esql); foreach (var c in query) { result.InnerHtml += c.CategoryName + "<br />"; } } /**//* SELECT [Extent1].[CategoryID] AS [CategoryID], [Extent1].[CategoryName] AS [CategoryName], [Extent1].[Description] AS [Description], [Extent1].[Picture] AS [Picture] FROM [dbo].[Categories] AS [Extent1] */ } private void Demo2() { using (var ctx = new NorthwindEntities()) { string esql = "select c.CategoryName from NorthwindEntities.Categories as c"; // ObjectQuery<T>()構造函數 - 根據 esql 創建一個 ObjectQuery ,返回 DbDataRecord 。(延遲) // System.Data.Objects.MergeOption枚舉 - 如何將此次查詢結果與之前同一 ObjectContext 的存在與內存的查詢結果做合並 // MergeOption.AppendOnly - 追加。默認值 // MergeOption.OverwriteChanges - 以新結果為准 // MergeOption.PreserveChanges - 以原結果為准 // MergeOption.NoTracking - 取消變更跟蹤,不會使用 ObjectStateManager,減少 執行查詢的時間,所有返回的實體將是分離的狀態(detached state) ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord> (esql, ctx, MergeOption.NoTracking); // 可以在 ObjectQuery<T> 上使用 Linq 方法或查詢語法 foreach (DbDataRecord item in query.Take(3)) { result.InnerHtml += item["CategoryName"].ToString() + "<br />"; } } /**//* SELECT [Limit1].[C1] AS [C1], [Limit1].[CategoryName] AS [CategoryName] FROM ( SELECT TOP (3) [Extent1].[CategoryName] AS [CategoryName], 1 AS [C1] FROM [dbo].[Categories] AS [Extent1] ) AS [Limit1] */ } private void Demo3() { using (var ctx = new NorthwindEntities()) { string esql = "select value count(c.CategoryID) from NorthwindEntities.Categories as c"; // ObjectQuery<簡單類型> 的示例(延遲) ObjectQuery<int> query = ctx.CreateQuery<int>(esql); result.InnerHtml += query.First().ToString() + "<br />"; } /**//* SELECT [Limit1].[A1] AS [C1] FROM ( SELECT TOP (1) COUNT([Extent1].[CategoryID]) AS [A1] FROM [dbo].[Categories] AS [Extent1] ) AS [Limit1] */ } private void Demo4() { using (var ctx = new NorthwindEntities()) { string esql = "select value c from NorthwindEntities.Categories as c"; // 延遲 ObjectQuery<Categories> query = ctx.CreateQuery<Categories>(esql); // ObjectQuery<T>.Execute() - 立即執行查詢。返回 ObjectResult<T> ObjectResult<Categories> queryResult = query.Execute (MergeOption.NoTracking); foreach (var c in queryResult) { result.InnerHtml += c.CategoryName + "<br />"; } } /**//* SELECT [Extent1].[CategoryID] AS [CategoryID], [Extent1].[CategoryName] AS [CategoryName], [Extent1].[Description] AS [Description], [Extent1].[Picture] AS [Picture] FROM [dbo].[Categories] AS [Extent1] */ } }