首页 文章

实体框架存储过程不可用

提问于
浏览
3

我在edmx文件中添加了对存储过程的引用,然后右键单击它并选择“Create Function Import”,它被添加到模型浏览器中EntityContainer下的Function Imports文件夹中 .

据我了解,我应该可以像这样使用它:

sampleEntities db = new sampleEntities();
db.SampleStoredProcedure();

但它没有显示在db对象上 . 我缺少一步吗?函数导入设置为public,没有返回值,以及我在展开它时可以看到的一个参数 .

2 回答

  • 7

    您的存储过程是否返回一个简单的(也就是标量)值?如果是这样,设计师will not generate the code for you

    如果将“返回类型”设置为简单类型,则不会自动为“函数导入”生成Visual Basic或C# .

    但是,这已得到修复in the newest version of the Entity Framework

    您可以像以前一样选择None和Scalar返回类型 . 但是,当创建“函数导入”时,会将一些新代码注入到模型代码后面的文件中,该代码将存储过程实现为对ObjectContext本身的操作 .

  • 3

    您可以使用EntityCommand类执行存储过程,将新存储过程添加到实体数据模型,然后将其添加为函数并命名,然后执行存储过程:

    public bool ExecuteCMD(string Command) 
    {
        using (var entities = new DbEntities())
        {
            var conn = new System.Data.EntityClient.EntityConnection(entities.Connection.ConnectionString);
            try
            {
                conn.Open();
                using (EntityCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "DbEntities." + Command;
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }
    }
    

相关问题