[C# ModelToSql http://discuz.tangjunfei.com/forum.php?mod=viewthread&tid=4 (出处: TangZhiZzz!)](C# ModelToSql http://discuz.tangjunfei.com/forum.php?mod=viewthread&tid=4 (出处: TangZhiZzz!))
public class ModelToSql { public static string CreateSelectSql<T>(T mdoel) { return "Select * From " + GetTableName<T>(); } public static string CreateInsertSql<T>(T mdoel) { Type type = typeof(T); string[] pName = type.GetProperties().Where(m => !m.Name.Equals("ID")).Select(m => "[" + m.Name + "]").ToArray(); string strSqlName = string.Join(",", pName); string[] pValue = type.GetProperties().Where(m => !m.Name.Equals("ID")).Select(m => "[" + m.GetValue(mdoel) + "]").ToArray(); string strSqlValue = string.Join(",", pValue); return "insert into " + GetTableName<T>() + " ( " + strSqlName + " ) values (" + strSqlValue + ")"; } public static string CreateUpdateSql<T>(T mdoel) { Type type = typeof(T); bool isHasID = type.GetProperties().Where(m => m.Name.Equals("ID")).Count() > 0 ? true : false; if (!isHasID) return "model not find ID"; int ID = (int)type.GetProperties().Where(m => m.Name.Equals("ID")).FirstOrDefault().GetValue(mdoel); string[] pKV = type.GetProperties().Where(m => !m.Name.Equals("ID")).Select(m => m.Name + "=" + GetPropertyInfoValue(m, mdoel)).ToArray(); string strSqlKV = string.Join(",", pKV); return "UPDATE " + GetTableName<T>() + " Set " + strSqlKV + " Where ID = " + ID; } public static string GetPropertyInfoValue<T>(PropertyInfo propertyInfo, T model) { string type = propertyInfo.PropertyType.Name; string str = string.Empty; switch (type) { case "String": str = "'" + propertyInfo.GetValue(model).ToString() + "'"; break; case "DateTime": str = "'" + propertyInfo.GetValue(model).ToString() + "'"; break; case "Boolean": str = propertyInfo.GetValue(model).ToString(); break; default: break; } return str; } public static T GetAttributeForModel<T>(Type type) where T : Attribute { var attrs = type.GetCustomAttributes(typeof(T), true); if (attrs.Any()) { return (T)attrs.Where(m => m.GetType() == typeof(T)).FirstOrDefault(); } return null; } public static string GetTableName<T>() { var Table = GetAttributeForModel<TableNameAttribute>(typeof(T)); if (Table != null) { if (!string.IsNullOrWhiteSpace(Table.TableName)) { return Table.TableName; } } return typeof(T).Name; } }