EF 存储过程(下)

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

> 添加/修改存储过程

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

<Function Name="CustomerByCommandText" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="false" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo" >
          <CommandText>
            select c.* from Customers c,Orders o where c.CustomerID=o.CustomerID
          </CommandText>
        </Function>

然后,再找到csdl部分,添加如下代码:

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

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

<FunctionImportMapping FunctionImportName="CustomerByCommandText" FunctionName="NorthwindModel.Store.CustomerByCommandText"/>

最后,在实体模型的.cs文件里面,添加一个执行此存储过程的方法,代码如下:

public global::System.Data.Objects.ObjectResult<Customers> GetCustomerByCommandText()
{
    return base.ExecuteFunction<Customers>("CustomerByCommandText");
}

至此,修改完毕。
现在,我们就可以在代码使用刚才手工定义的存储过程了。如下代码所示:

public void GetCustomerByCmdText()
{
    using (var db = new NorthwindEntities())
    {
    var csts = db.GetCustomerByCommandText().Take(10).Skip(0);
    foreach (var c in csts)
        Console.WriteLine(c.CustomerID);
    }
}

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

> Output类型参数

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

CREATE PROCEDURE GetNameByCustomerId
 @CustomerId varchar(5),
 @ContactName varchar(30) output
AS
BEGIN
 SET NOCOUNT ON;
 SELECT @ContactName=ContactName
 FROM Customers
 WHERE CustomerID=@CustomerId;
END


然后,开始修改实体模型edmx文件。
先找到ssdl定义的部分,添加如下代码:

  <Function Name="GetNameByCustomerId" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="false" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo">
          <Parameter Name="CustomerId" Type="varchar" Mode="In" MaxLength="5"></Parameter>
          <Parameter Name="ContactName" Type="varchar" Mode="Out" MaxLength="30"></Parameter>
       </Function>

接着,在找到csdl定义的部分,添加如下代码:

 <FunctionImport Name="GetNameByCustomerId">
            <Parameter Name="CustomerId" Mode="In" Type="String" MaxLength="5"></Parameter>
            <Parameter Name="ContactName" Mode="Out" Type="String" MaxLength="30"></Parameter>
      </FunctionImport>


最后,找到msl定义的部分,添加如下代码:

<FunctionImportMapping FunctionImportName="GetNameByCustomerId" FunctionName="NorthwindModel.Store.GetNameByCustomerId"></FunctionImportMapping>

至此,实体模型emdx文件修改完毕。
接下来,我们需要在实体模型的.cs文件中,增加相应的调用方法。代码如下:

public partial class NorthwindEntities1
{
 
    //执行GetNameByCustomerId的方法
        public void GetNameByCustomerId(string CustomerId, out string ContactName)
        {
           ContactName = string.Empty;
            var Pars = new System.Data.EntityClient.EntityParameter[]
            {
                new System.Data.EntityClient.EntityParameter{ ParameterName="CustomerId", DbType=System.Data.DbType.String,Value=CustomerId},
                new System.Data.EntityClient.EntityParameter{ParameterName="ContactName", DbType=System.Data.DbType.String, Direction=System.Data.ParameterDirection.Output}
            };
            this.ExecuteNonQuery("GetNameByCustomerId", Pars);
            ContactName = Pars[1].Value.ToString();
 
        }
     
      //辅助方法,执行SQL命令
        private void ExecuteNonQuery(string functionName, System.Data.EntityClient.EntityParameter[] parameters)
        {
            System.Data.EntityClient.EntityCommand cmd = ((System.Data.EntityClient.EntityConnection)this.Connection).CreateCommand();
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddRange(parameters);
            cmd.CommandText = this.DefaultContainerName + "." + functionName;
            try
            {
                if (cmd.Connection.State != System.Data.ConnectionState.Open)
                    cmd.Connection.Open();
                cmd.ExecuteNonQuery();
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
}

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

public void OutputTest()
{
    using (var db = new NorthwindModel.NorthwindEntities1())
    {
    string contactname = string.Empty;
    db.GetNameByCustomerId("ALFKI", out contactname);
    Assert.IsTrue(!string.IsNullOrEmpty(contactname));
    Console.WriteLine(contactname);
    }
}

至此,我们便可以使用Output类型的输出参数了

 

posted @ 2014-12-31 17:25  悠悠清风~  阅读(361)  评论(0编辑  收藏  举报