C# 匿名类充当ORM操作数据库

最终代码:

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());
        }

}


如果转载,请注明出处.

javasuki@hotmail.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值