In EF (Entity Framework), there are mainly two ways to execute the stored procedure.
Execute Command
Normally, all developers do it this way.
Execute Command
Normally, all developers do it this way.
- var affectedDatas = context.Database.ExecuteSqlCommand("store_procedure_name @field1, @field2, @field3, ...",
- new SqlParameter("@field1", "value1"),
- new SqlParameter("@field2", "value2"),
- new SqlParameter("@field3", "value3"),
- ...);
In the above scenario, if more parameters are added in the stored procedure, then we have to add that newly created parameter in this statement also. If we forget to add that, it will throw an error.
To overcome this type of mistake, we can create an Extension method by which we can simplify this operation.
- public class SQLQueryClass {
- public string Command {
- get;
- set;
- }
- public SqlParameter[] Parameters {
- get;
- set;
- }
- }
- public static SQLQueryClass CreateCommandAndParameters(this object obj) {
- var props = obj.GetType().GetProperties();
- var result = new SQLQueryClass();
- var lstSqlParameters = new List();
- var lstName = new List();
- for (int i = 0; i < props.Length; i++) {
- var propertyName = $ "@{ props[i].Name}";
- var value = props[i].GetValue(obj, null);
- lstName.Add(propertyName);
- var sqlParameter = new SqlParameter(propertyName, value ? ? DBNull.Value);
- lstSqlParameters.Add(sqlParameter);
- }
- result.Command = string.Join(", ", lstName);
- result.Parameters = lstSqlParameters.ToArray();
- return result;
- }

Mahesh AllePosted Aug 29, 2018, 10:02 AM
I have question. You have created an extension method of object class. That means, this extension method will available to all the class objects. (i.e. when ever I created object of any class, then this extension method will be available). This is not a good solution as we are providing this extension method all the class objects that actually not needed. Do you have any other way to implement this solution? May be can you create this extension method in other class instead on base class object. Just this.....
Wook Jin LeePosted Aug 23, 2018, 3:07 AM
Wow. that is so useful. thank you.