Monday 23 June 2014

Code To Insert Data From Any Class using Sp Automated

1)      No tension of Class Type for Calling Sp
2)      Write 1 function for Data Base insertion and call that from  other classes .
3)      No tension for remembering column names.
4)      No Lengthy code
5)      Write small function
6)      Write Stored Procedure
7)      Just Remember : Create a class that must has the property  equivalent to table column name.
8)      Same name of the property and equivalent data type  then you don’t need to type cast by extra coding.
Code Like This Will Make a Structure of Your Application That will enable you to write small Code.
That powerful function is :
  public static Boolean ExecuteSp(List<Object> paramlist, String SpName)
        {

    SqlConnection Conn = new SqlConnection(DbAcccess.ConnectionString());
            try 
            {
                foreach (var param in paramlist)
                {
                   
                    SqlCommand Comb = new SqlCommand(SpName, Conn);
                    Comb.CommandType = CommandType.StoredProcedure;
                    Type ObjectType = param.GetType();
                    IList<PropertyInfo> props = new   List<PropertyInfo>(ObjectType.GetProperties());

                    foreach (PropertyInfo ItemProp in props)
                    {
                        object Propvalue = ItemProp.GetValue(param, null);
Comb.Parameters.Add("@" + ItemProp.Name.ToString(),ItemProp.PropertyType).Value = Propvalue;
                    }
                    Conn.Open();
                    Comb.ExecuteNonQuery();
                    Conn.Close();
                }
                return true;


            }
            catch (Exception Ex)
            {
                return false;
            }
            finally
            {
                Conn.Close();
            }
        }



To Work with this code you have to import the name space  System.Reflection.
This Namespace has the definition  of PropertyInfo.
Using this you can just get the value of the properties , name and type of the properties. This will do the magic for you.
You will pass the List of objects and SP name.

That means If you want to save more than 1 objects in a single function you don’t need to write loop explicitly you just pass the array of object and your work will be done.

Sample User Saving Code:
       public String SaveUser(clsUser paramUser)
        {
            List<object> lstUser = new List<object>();
            lstUser.Add(paramUser);
            Boolean Res = DbAcccess.ExecuteSp(lstUser, StaticSpName.SpInsertUser);
            if (Res == false)
            {
                return "Error In Saving User.";
            }
            else
            {
                return "User Saved Successfully.";
            }
  }

Here I am saving single object .You can save multiple objects using List<object>.


Try this code and please give your comments