Welcome

首页 / 软件开发 / .NET编程技术 / VS 2008 sp1 + .NET 3.5 sp1(4)

VS 2008 sp1 + .NET 3.5 sp1(4)2011-11-23 博客园 webabcdEntity 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    */  }}