天天看点

再接再厉VS 2008 sp1 + .NET 3.5 sp1(4) - Entity Framework(实体框架)之EntityClient, ObjectQuery

<a href="http://webabcd.blog.51cto.com/1787395/341154" target="_blank">[索引页]</a>

<a href="http://down.51cto.com/data/99915">[源码下载]</a>

再接再厉VS 2008 sp1 + .NET 3.5 sp1(4) - Entity Framework(实体框架)之EntityClient, ObjectQuery

介绍

以Northwind为示例数据库,ADO.NET Entity Framework之详解EntityClient, ObjectQuery

EntityConnection - 与存储模型的连接

EntityCommand - 对 EDM 执行的命令

EntityParameter - 配置 EntityCommand 的参数

EntityDataReader - 以只读、只进的数据流的方式获取数据(内存中始终只有一行)。相当于SqlDataReader

ObjectQuery&lt;T&gt; - 通过 Entity SQL 或 查询语法 或 Linq 方法对概念模型做查询

ObjectContext.CreateQuery&lt;T&gt;(Entity SQL) - 根据 esql 创建一个 ObjectQuery&lt;T&gt; 。(延迟)

示例

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 

void Page_Load() void Page_Load(object sender, EventArgs e) 

        { 

                if (!Page.IsPostBack) 

                { 

                        Demo(); 

                        result.InnerHtml += "&lt;br /&gt;"; 

                        Demo2(); 

                        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() + "&lt;br /&gt;"; 

                                                } 

                                        } 

                                } 

                        } 

                        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")) 

                                        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); 

                                                        result.InnerHtml += edr.GetString(1) + "&lt;br /&gt;"; 

                exec sp_executesql N'SELECT    

                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)) 

                                        // 调用存储过程(需要先做好映射,然后指定概念模型中的函数名称) 

                                        cmd.CommandType = CommandType.StoredProcedure; 

                                        cmd.CommandText = "NorthwindEntities.GetCategory"; 

                                        param.ParameterName = "CategoryID"; 

                exec [dbo].[spSelectCategory] @CategoryID=1    

}

2、关于ObjectQuery

ObjectQuery.aspx.cs

using System.Data.Common; 

public partial class EntityFramework_ObjectQuery : System.Web.UI.Page 

                        Demo4(); 

void Demo() void Demo() 

                using (var ctx = new NorthwindEntities()) 

                        string esql = "select value c from NorthwindEntities.Categories as c"; 

                        // ObjectQuery&lt;T&gt; - 通过 Entity SQL 或 查询语法 或 Linq 方法对概念模型做查询 

                        // ObjectContext.CreateQuery&lt;T&gt;(Entity SQL) - 根据 esql 创建一个 ObjectQuery&lt;T&gt; 。(延迟) 

                        ObjectQuery&lt;Categories&gt; query = ctx.CreateQuery&lt;Categories&gt;(esql); 

                        foreach (var c in query) 

                                result.InnerHtml += c.CategoryName + "&lt;br /&gt;"; 

void Demo2() void Demo2() 

                        string esql = "select c.CategoryName from NorthwindEntities.Categories as c"; 

                        // ObjectQuery&lt;T&gt;()构造函数 - 根据 esql 创建一个 ObjectQuery ,返回 DbDataRecord 。(延迟) 

                        // System.Data.Objects.MergeOption枚举 - 如何将此次查询结果与之前同一 ObjectContext 的存在与内存的查询结果做合并 

                        //         MergeOption.AppendOnly - 追加。默认值 

                        //         MergeOption.OverwriteChanges - 以新结果为准 

                        //         MergeOption.PreserveChanges - 以原结果为准 

                        //         MergeOption.NoTracking - 取消变更跟踪,不会使用 ObjectStateManager,减少执行查询的时间,所有返回的实体将是分离的状态(detached state) 

                        ObjectQuery&lt;DbDataRecord&gt; query = new ObjectQuery&lt;DbDataRecord&gt;(esql, ctx, MergeOption.NoTracking); 

                        // 可以在 ObjectQuery&lt;T&gt; 上使用 Linq 方法或查询语法 

                        foreach (DbDataRecord item in query.Take(3)) 

                                result.InnerHtml += item["CategoryName"].ToString() + "&lt;br /&gt;"; 

                [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] 

void Demo3() void Demo3() 

                        string esql = "select value count(c.CategoryID) from NorthwindEntities.Categories as c"; 

                        // ObjectQuery&lt;简单类型&gt; 的示例(延迟) 

                        ObjectQuery&lt;int&gt; query = ctx.CreateQuery&lt;int&gt;(esql); 

                        result.InnerHtml += query.First().ToString() + "&lt;br /&gt;"; 

                [Limit1].[A1] AS [C1] 

                FROM ( SELECT TOP (1)    

                        COUNT([Extent1].[CategoryID]) AS [A1] 

                )    AS [Limit1]    

void Demo4() void Demo4() 

                        // 延迟 

                        // ObjectQuery&lt;T&gt;.Execute() - 立即执行查询。返回 ObjectResult&lt;T&gt; 

                        ObjectResult&lt;Categories&gt; queryResult = query.Execute(MergeOption.NoTracking); 

                        foreach (var c in queryResult) 

                FROM [dbo].[Categories] AS [Extent1]    

OK

     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/341462,如需转载请自行联系原作者