問題
使用 泛型產生物件Update SQL
解決方法
internal string GetUpdateString<T>(T obj) where T : class
{
PropertyInfo[] srcFields = obj.GetType().GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
List<string> columnString = new List<string>();
foreach (var property in srcFields)
{
if (((DescriptionAttribute)((TypeDescriptor.GetProperties(this)[property.Name].Attributes)[typeof(DescriptionAttribute)])).Description == "")
{
if (property.GetValue(obj, null) != null)
{
if (property.PropertyType == typeof(decimal) ||
property.PropertyType == typeof(double) ||
property.PropertyType == typeof(int))
{
columnString.Add(_getFieldName(property.Name)+ "=" + property.GetValue(obj, null).ToString());
}
else if (property.PropertyType == typeof(string))
columnString.Add(_getFieldName(property.Name)+"='" + property.GetValue(obj, null).ToString() + "'");
}
else
columnString.Add(_getFieldName(property.Name) + "=" + "null");
}
}
if (columnString.Count > 0)
{
string sql = string.Format(@"
UPDATE {0}
SET {1}
", srcFields[0].DeclaringType.Name, string.Join(",", columnString.ToArray()));
return sql;
}
else
throw new ArgumentNullException(string.Format("發生錯誤於:{0} 物件未實體化", this.GetType().Name));
}
沒有留言:
張貼留言