在实体框架表值函数?实体、函数、框架

2023-09-04 07:18:04 作者:子兮分袂

是否有可能调用使用表值函数(TVF)实体框架?

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

我在我的数据库中定义了三种TVFs,他们没有在实体框架的模型显示,或者在更新的数据库模型向导。

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.

这是很容易可以做到这一点的LINQ到SQL,您只需将TVF到设计界面,但在L2E它似乎并不像它的可能。

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.

到目前为止,我还没有发现任何东西,甚至提到TVFs和实体框架在一起。

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

推荐答案

如果你只需要得到的结果作为一个类型列表从TVF在code-首先4.3你可以设置你的的DbContext例如,一个帮手

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; }
        }
    }

该称呼其为

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);
}