Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Scalar valued function in entity framework 6

How can I call a scalar function in entity framework 6 ? I have tried the following code

        using (MhEntities DContext = new MhEntities())
        {
            var Account_IdParameter = Account_Id.HasValue ? new ObjectParameter("Account_Id", Account_Id) : new ObjectParameter("Account_Id", typeof(long));
            string res = ((IObjectContextAdapter)DContext).ObjectContext.CreateQuery<string>("MoneyforHealthEntities.Fn_LEVEL0_Acount_Id", Account_IdParameter).FirstOrDefault();
            return Convert.ToInt64(res);
        }
like image 660
Liju Avatar asked Jul 30 '15 16:07

Liju


People also ask

How do you call a scalar valued function?

Scalar-valued functions can be executed by using the EXECUTE statement. If you EXECUTE a function rather than use it in a SELECT statement or constraint, you can leave out the schema name in the function name, and it will look in the dbo schema followed by the users default schema.

How do you call a function in Entity Framework?

Step 1: Create an entity class which inherits “DbContext” class. Step 2: The following is the structure of the database with table and stored procedure. Step 3: Create a class to store the returned tabular value. Step 4: Create an object for the entity above and method to call a function.

How do you call a scalar valued function from a stored procedure?

Scalar-valued functions may be invoked where scalar expressions are used, including computed columns and CHECK constraint definitions. When invoking scalar-valued functions, at minimum use the two-part name of the function.

How do you select a scalar valued function in SQL Server?

If you want to use select function() you must use a scalar function. Show activity on this post. Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.


1 Answers

No need to use ObjectContext to do this. Also, I don't think you can simply pass in the name of the function, you need to give it complete, valid SQL.

So I would try something like this instead:

using (MhEntities DContext = new MhEntities())
{
    string res = DContext.Database.SqlQuery<string>("SELECT MoneyforHealthEntities.Fn_LEVEL0_Acount_Id(@p0)", Account_Id).FirstOrDefault();
    return Convert.ToInt64(res);
}

Since you didn't give any details about which database you are using, or the exact function definition, it's possible that the above may need further tweaking. But it should at least give you the basic idea.

like image 179
sstan Avatar answered Nov 09 '22 17:11

sstan