Friday, June 14, 2013

Calling User Defined Function in Entity Framework 5

public string ExecuteUserDefinedFunctionReturningScalarStringValue(int inputValue)
{
    var query = "SELECT [dbo].[UserDefinedFunctionName]({0})";
    object[] param = { inputValue };
    var outputString = Context.Database.SqlQuery<string>(query, param).FirstOrDefault();

    return outputString;
}

Calling Store Procedure in Entity Framework 5

Model.Context.cs:

public virtual int DbStoreProcedureName(ObjectParameter output_string, Nullable<int> inputId)
{
    var inputIdParameter = inputId.HasValue ?
        new ObjectParameter("inputParam1", inputId) :
        new ObjectParameter("inputParam1", typeof(int));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("DbStoreProcedureName", output_string, inputIdParameter);
}       
       
Usage:

var inputValue = 5;
var outputParam = new ObjectParameter("output_string", typeof(string));
Context.DbStoreProcedureName(outputString, intputValue);
var outputString = outputParam.Value.ToString();