Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework with optional parameters?

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.

like image 779
John S Avatar asked Jun 20 '13 18:06

John S


1 Answers

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

like image 169
Sergey Berezovskiy Avatar answered Sep 20 '22 23:09

Sergey Berezovskiy