ameByCustomerId" 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();
}
}
}
现在,所有的修改工作都做完了。接下来,我们就可以在代码中直接调用此存储过程了。示例代码如下:
[Test]
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类型的输出参数了。 |