Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table-Valued Functions in Entity Framework?

Is it possible to call a Table-Valued Function (TVF) using Entity Framework?

I have three TVFs defined in my database, and they do not show up in the Entity Framework's model, or in the "Update Model from Database" wizard.

It's easily possible to do this in Linq-to-SQL, you simply drag the TVF onto the design surface, but in L2E it doesn't seem like it's possible.

So far I haven't found anything that even mentions TVFs and Entity Framework together.

like image 663
Joshua Tompkins Avatar asked Aug 18 '09 15:08

Joshua Tompkins


People also ask

How do you call a table-valued function in Entity Framework?

Step 1 − Select the Console Application from the middle pane and enter TableValuedFunctionDemo in the name field. Step 2 − In Server explorer right-click on your database. Step 3 − Select New Query and enter the following code in T-SQL editor to add a new table in your database.

What are table-valued functions?

A table function, also called a table-valued function (TVF), is a user-defined function that returns a table. You can use a table function anywhere that you can use a table. Table functions behave similarly to views, but a table function can take parameters.

What is table-valued function and scalar valued functions?

There are two main types of user-defined functions in SQL based on the data they return: Scalar functions: These types of functions return a single value, i.e float, int, varchar, datetime, etc. Table-Valued functions: These functions return tables.


1 Answers

If you just need to get the results as a typed list from a TVF in Code-First 4.3 you can setup a helper on your DbContext e.g.

    public class ModelDbContext : DbContext
    {

        public IEnumerable<TOutput> FunctionTableValue<TOutput>(string functionName, SqlParameter[] parameters)
        {
                parameters = parameters ?? new SqlParameter[] { };

                string commandText = String.Format("SELECT * FROM dbo.{0}", String.Format("{0}({1})", functionName, String.Join(",", parameters.Select(x => x.ParameterName))));

                return  ObjectContext.ExecuteStoreQuery<TOutput>(commandText, parameters).ToArray();
        }

        private ObjectContext ObjectContext
        {
            get { return (this as IObjectContextAdapter).ObjectContext; }
        }
    }

The call it as

using (var db = new ModelDbContext())
{
    var parameters = new SqlParameter[]
    {
        new SqlParameter("@Id", SqlDbType.Int),
    };
    parameters[0].Value = 1234;

    var items = db.FunctionTableValue<Foo>("fn_GetFoos", parameters);
}
like image 144
Adam Avatar answered Oct 13 '22 21:10

Adam