最终代码:
var user = new { UName = "foo", Birthday = DateTime.Now };
string tblName = "[User]";
tblName.DBExecuteHelper().DataCreate(user);
具体实现,去除了其它更改,输出代码,最短最有效的代码,读者可以自己扩充
DBExecuteHelper()方法是扩展string的类中定义
public static class VarStringExtension
{
public static Execute DBExecuteHelper(this string tableName)
{
return Execute.GetExecute(tableName);
}
}
public class Execute
{
string TableName;
internal Execute()
{
}
internal static Execute GetExecute(string tableName)
{
return new Execute() { TableName = tableName };
}
string[] AutoFields;
public void DataCreate(object objAnonymous, params string[] autoFieldNames)
{
this.AutoFields = autoFieldNames;
//有效性检查代码省去 throw new ArgumentException("objAnonymous");
DbConnection dbConn = new SqlConnection(); //连接字符串...
DbCommand cmd = dbConn.CreateCommand();
fillAnonymous2Command(this.TableName, objAnonymous, cmd, this.AutoFields);
cmd.ExecuteNonQuery();
}
internal void fillAnonymous2Command(string tableName, object objAnonymous, DbCommand cmd, params string[] autoFieldNames)
{
string mark = "@";
string sqlInsert = "insert into {0}({1}) values({2})";
StringBuilder insertFlds = new StringBuilder();
StringBuilder insertVals = new StringBuilder();
bool bInsertFirst = true;
PropertyInfo[] propInfos = objAnonymous.GetType().GetProperties();
foreach (PropertyInfo propInfo in propInfos)
{
var query = from word in autoFieldNames
where word.ToLower().CompareTo(propInfo.Name.ToLower()) == 0
select word;
if (query.Count<string>() > 0) continue;
insertFlds.Append(bInsertFirst ? propInfo.Name : "," + propInfo.Name);
insertVals.Append(bInsertFirst ? mark + propInfo.Name : "," + mark + propInfo.Name);
if (bInsertFirst) bInsertFirst = false;
DbParameter param = cmd.CreateParameter();
param.ParameterName = mark + propInfo.Name;
param.Value = propInfo.GetValue(objAnonymous, null);
if (param.Value == null)
{
param.Value = System.DBNull.Value;
}
cmd.Parameters.Add(param);
}
cmd.CommandText = string.Format(sqlInsert, tableName, insertFlds.ToString(), insertVals.ToString());
}
}
如果转载,请注明出处.