Yasin Yasin - 3 months ago 20
C# Question

How to call And get result of scalar valued function using entity framework

I am using entity framework 6.0.

I am having scalar valued function in sql server signatured as


fn_CartAmount(@CartId bigint) RETURNS decimal(18,2)



I want to call this function from entityframework and get its result.

Answer

You could try something like :

    public decimal GetCartAmount(int cartId)
    {

        var returnCode = new SqlParameter("@ReturnCode", SqlDbType.Bit) { Direction = ParameterDirection.Output };

        object[] parameters =
        {
            new SqlParameter(@"CartId", SqlDbType.BigInt) {Value = cartId}
            , returnCode
        };

        string command = string.Format("exec @ReturnCode = dbo.fn_CartAmount @CartId");
        Database.ExecuteSqlCommand(command, parameters);


        return (decimal)returnCode.Value;
    }