7 dec 2011

convert object to insert query or Create table statement

Okey I know, the code represented here is not the code that you want to use for the CRUD in an ERP system. bud sometimes things need to go fast.



example

string insertquery = Myobject.ToSqlQuery();


put these functions in a public static class file:

  public static string ToSqlQuery(this T primary)
        {
            int counter = 0;
            string Columnstatement = "INSERT INTO " + typeof(T).Name + "  (";
            string ValueStatement = " VALUES ( ";
            foreach (var pi in typeof(T).GetProperties())
            {

                string priValue = string.Empty;
                PropertyInfo pil = (PropertyInfo)pi;
                try
                {
                    priValue = pi.GetGetMethod().Invoke(primary, null).ToString();
                }
                catch (Exception)
                {
                                    
                }


                if (priValue != string.Empty)
                {
                    if (counter > 0)
                    {
                        ValueStatement += ",";
                        Columnstatement += ",";
                    }
                    Columnstatement += "[" + pil.Name + "]";
                    ValueStatement += "'" + priValue + "'";
                    counter++;
                }
              
                                    
            }

            return Columnstatement + ") " + ValueStatement + ")";
        }




 
        public static string ToSqlCreateTable(this T primary)
        {
            int counter = 0;
            string Columnstatement = "CREATE TABLE " + "TABLENAME  (";
            string ValueStatement = "VALUES ( ";
            foreach (var pi in typeof(T).GetProperties())
            {
                PropertyInfo pil = (PropertyInfo)pi;
                if (counter > 0)
                {
                    Columnstatement += ",";
                }
                Columnstatement += "[" + pil.Name + "]" + "  VARCHAR(254)";
                counter++;
            }
            Columnstatement += ")";
            return Columnstatement;
        }

Geen opmerkingen:

Een reactie posten