Entity Framework with optional parameters?

僤鯓⒐⒋嵵緔 提交于 2019-12-01 16:05:42

问题


Using Entity Framework 5 is it possible to use a stored proc with optional parameters such that you do not have to add a null for each unused parameter?

The stored proc I have to use has 87 parameters only 2 of which are required. I really hate the idea of having to put 85 nulls in each call.


回答1:


You can use ObjectContext.ExecuteFunction method (DbContext is a wrapper over ObjectContext) to execute some stored procedure and pass list of parameters:

FooEntities db = new FooEntities();
var objectContext = ((IObjectContextAdapter)db).ObjectContext;
// create all parameters you need
var name = new ObjectParameter("Name", "Lazy");
var age = new ObjectParameter("Age", 29);

// call stored procedure with these two parameters only
var result = objectContext.ExecuteFunction<Result>("ProcedureName", name, age);

You can wrap this code into extension method for your DbContext:

public static Result ProcedureName(this FooEntities db, name, age)
{
    // code above
}

Usage will be like: var result = db.ProcedureName("Lazy", 29);




回答2:


I am demonstrating @Francisco Goldenstein comment on the answer. The order in "EXEC SP_MySP @One, @Two, @Three, @Four" statement should match your stored procedure's parameter. The order of paraOne, paraTwo, etc doesn't matter.

         public List<MySPEntity> GetMyData(int thirdValue, string firstValue)
        {
                var paraOne = new SqlParameter("@One", firstValue);
                var paraTwo = new SqlParameter("@Two", DBNull.Value);
                var paraThree = new SqlParameter("@Three", thirdValue);
                var paraFour = new SqlParameter("@Four", DBNull.Value);

                var result = DataContext.Database.SqlQuery<MySPEntity>("EXEC SP_MySP @One, @Two, @Three, @Four"
                , paraTwo, paraOne, paraFour,paraThree).ToList();

                return result;
          
        }


来源:https://stackoverflow.com/questions/17220593/entity-framework-with-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!