public static string GetUpdateSQL(T model) { T obj = new T(); PropertyInfo[] protyInColl = obj.GetType().GetProperties(); var types = typeof(T); MethodInfo[] methods = types.GetMethods(); PropertyInfo[] Propertys = model.GetType().GetProperties(); string primaryKey = string.Empty; string primaryKeyValue = string.Empty; string Value = string.Empty; int rowIndex = 0; foreach (var property in Propertys) { rowIndex++; if (rowIndex == 1) { primaryKey = property.Name; try { primaryKeyValue = property.GetValue(model, null).ToString(); } catch { throw new Exception("实体类第一个字段必须为主键,主键必须有值!"); } continue; } if (Value == string.Empty) { try { Value = property.Name + string.Format("='{0}'", SqlInput.InputString(property.GetValue(model, null).ToString())); } catch { Value = property.Name + string.Format("=null"); } } else { try { Value += "," + property.Name + string.Format("='{0}'", SqlInput.InputString(property.GetValue(model, null).ToString())); } catch { Value += "," + property.Name + string.Format("=null"); } } } return(string.Format("update {0} set {1} where {2}='{3}'", types.Name, Value, primaryKey, primaryKeyValue)); }
public static string GetInsertSQL(T model) { T obj = new T(); PropertyInfo[] protyInColl = obj.GetType().GetProperties(); var types = typeof(T); MethodInfo[] methods = types.GetMethods(); PropertyInfo[] Propertys = model.GetType().GetProperties(); string Proper = string.Empty; string Value = string.Empty; int rowIndex = 0; foreach (var property in Propertys) { rowIndex++; if (Proper == string.Empty) { Proper = property.Name; } else { Proper += "," + property.Name; } if (rowIndex == 1) { Value = "getnewid('" + types.Name + "')"; } else { try { Value += string.Format(",'{0}'", SqlInput.InputString(property.GetValue(model, null).ToString())); } catch { Value += string.Format(",null"); } } } return(string.Format("insert into {0} ({1}) values ({2})", types.Name, Proper, Value)); }