Entity framework 调用存储过程

目前,EF对存储过程的支持并不完善。存在以下问题:

l        EF不支持存储过程返回多表联合查询的结果集。

l        EF仅支持返回返回某个表的全部字段,以便转换成对应的实体。无法支持返回部分字段的情况。

l        虽然可以正常导入返回标量值的存储过程,但是却没有为我们自动生成相应的实体.cs代码,我们还是无法在代码中直接调用或使用标量存储过程

l        EF不能直接支持存储过程中Output类型的参数。

l        其他一些问题。

本节,我们将学习如何手动添加/修改存储过程,如何使EF能够支持Output类型的参数。

l        添加/修改存储过程

有时候,某个SQL语句比较复杂,但是数据库中又没有定义相应的存储过程。这个时候,我们又想使上层代码比较简单、方便的方式来完成此项任务。那么,此时,我们便可以手工在实体模型(.edmx文件)中添加自己需要的存储过程了。这样既方便上层调用又方便后期的修改。

以手动修改实体模型edmx文件,添加名为CustomerByCommandText的存储过程为例。具体步骤如下:

修改实体模型文件,找到ssdl部分,添加如下代码:
  1.         <Function Name="CustomerByCommandText" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="false" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo" >

  2.           <CommandText>

  3.             select c.* from Customers c,Orders o where c.CustomerID=o.CustomerID

  4.           </CommandText>

  5.         </Function>
复制代码
然后,再找到csdl部分,添加如下代码:

<FunctionImport Name="CustomerByCommandText" EntitySet="Customers" ReturnType="Collection(NorthwindModel.Customers)"></FunctionImport>

接着,找到msl部分,添加如下代码:

<FunctionImportMapping Functi Functi/>

最后,在实体模型的.cs文件里面,添加一个执行此存储过程的方法,代码如下:
  1.         public global::System.Data.Objects.ObjectResult<Customers> GetCustomerByCommandText()

  2.         {

  3.             return base.ExecuteFunction<Customers>("CustomerByCommandText");

  4.         }
复制代码
至此,修改完毕。

现在,我们就可以在代码使用刚才手工定义的存储过程了。如下代码所示:
  1. [Test]

  2.         public void GetCustomerByCmdText()

  3.         {

  4.             using (var db = new NorthwindEntities())

  5.             {

  6.                 var csts = db.GetCustomerByCommandText().Take(10).Skip(0);

  7.                 foreach (var c in csts)

  8.                     Console.WriteLine(c.CustomerID);

  9.             }

  10.         }
复制代码
其实,关键的地方就是CommandText这个部分的内容,它里面就是要执行的SQL语句。另外,我们可以在修改实体模型emdx文件的同时,我们可以看到所有的实体类查询的SQL语句命令都可以在edmx文件里找到,我们都可以进行相应的修改。

l        Output类型参数

在实际应用当中,很多时候,我们需要使用output类型的存储过程参数,以便返回我们需要的值。但是,目前,EF不能直接支持output类型的存储过程参数。为此,我们需要对实体模型进行修改,以便使其支持output类型的输出参数。具体过程如下:

在数据库中建立一个为名的GetNameByCustomerId存储过程,代码如下:
  1. CREATE PROCEDURE GetNameByCustomerId

  2. @CustomerId varchar(5),

  3. @ContactName varchar(30) output

  4. AS

  5. BEGIN

  6. SET NOCOUNT ON;

  7. SELECT @ContactName=ContactName

  8. FROM Customers

  9. WHERE CustomerID=@CustomerId;

  10. END
复制代码
然后,开始修改实体模型edmx文件。

先找到ssdl定义的部分,添加如下代码:
  1.       <Function Name="GetNameByCustomerId" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="false" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo">

  2.           <Parameter Name="CustomerId" Type="varchar" Mode="In" MaxLength="5"></Parameter>

  3.           <Parameter Name="ContactName" Type="varchar" Mode="Out" MaxLength="30"></Parameter>

  4.       </Function>
复制代码
接着,在找到csdl定义的部分,添加如下代码:
  1.       <FunctionImport Name="GetNameByCustomerId">

  2.             <Parameter Name="CustomerId" Mode="In" Type="String" MaxLength="5"></Parameter>

  3.             <Parameter Name="ContactName" Mode="Out" Type="String" MaxLength="30"></Parameter>

  4.       </FunctionImport>
复制代码
最后,找到msl定义的部分,添加如下代码:
  1. <FunctionImportMapping FunctionImportName="GetNameByCustomerId" FunctionName="NorthwindModel.Store.GetNameByCustomerId"></FunctionImportMapping>
复制代码
至此,实体模型emdx文件修改完毕。

接下来,我们需要在实体模型的.cs文件中,增加相应的调用方法。代码如下:
  1. public partial class NorthwindEntities1

  2. {



  3. //执行GetNameByCustomerId的方法

  4.         public void GetNameByCustomerId(string CustomerId, out string ContactName)

  5.         {

  6.           ContactName = string.Empty;

  7.             var Pars = new System.Data.EntityClient.EntityParameter[] 

  8.             {

  9.                 new System.Data.EntityClient.EntityParameter{ ParameterName="CustomerId", DbType=System.Data.DbType.String,Value=CustomerId},

  10.                 new System.Data.EntityClient.EntityParameter{ParameterName="ContactName", DbType=System.Data.DbType.String, Direction=System.Data.ParameterDirection.Output}

  11.             };

  12.             this.ExecuteNonQuery("GetNameByCustomerId", Pars);

  13.             ContactName = Pars[1].Value.ToString();



  14.         }

  15.       

  16.       //辅助方法,执行SQL命令

  17.         private void ExecuteNonQuery(string functionName, System.Data.EntityClient.EntityParameter[] parameters)

  18.         {

  19.             System.Data.EntityClient.EntityCommand cmd = ((System.Data.EntityClient.EntityConnection)this.Connection).CreateCommand();

  20.             cmd.CommandType = System.Data.CommandType.StoredProcedure;

  21.             cmd.Parameters.AddRange(parameters);

  22.             cmd.CommandText = this.DefaultContainerName + "." + functionName;

  23.             try

  24.             {

  25.                 if (cmd.Connection.State != System.Data.ConnectionState.Open)

  26.                     cmd.Connection.Open();

  27.                 cmd.ExecuteNonQuery();

  28.             }

  29.             catch (System.Exception)

  30.             {

  31.                 throw;

  32.             }

  33.             finally

  34.             {

  35.                 cmd.Connection.Close();

  36.             }

  37.         }

  38. }
复制代码
现在,所有的修改工作都做完了。接下来,我们就可以在代码中直接调用此存储过程了。示例代码如下:
  1. [Test]

  2.         public void OutputTest()

  3.         {

  4.             using (var db = new NorthwindModel.NorthwindEntities1())

  5.             {

  6.                 string contactname = string.Empty;

  7.                 db.GetNameByCustomerId("ALFKI", out contactname);

  8.                 Assert.IsTrue(!string.IsNullOrEmpty(contactname));

  9.                 Console.WriteLine(contactname);

  10.             }

  11.         }
复制代码
至此,我们便可以使用Output类型的输出参数了。
原文地址:https://www.cnblogs.com/jordan2009/p/2593166.html