Public classDalinsertupdate<t>whereT:New() { /// <summary> ///inserting non-(keyattribute) attributes into the specified table by model/// </summary> /// <param name= "TableName" >the name of the table to insert into</param> /// <param name= "Model" >the model to insert</param> /// <returns></returns> Public intInsert (stringTableName, T Model) { varName =NewStringBuilder (); varValue =NewStringBuilder (); varParame =NewList<sqlparameter>(); Propertyinfo[] Propertys=Model.gettype (). GetProperties (); foreach(varIteminchpropertys) { if(NULL==item. GetCustomAttribute (typeof(Keyattribute))) {Name.append (item. Name). Append (","); Value.append ("@"). Append (item. Name). Append (","); Parame.add (NewSqlParameter ("@"+item. Name,item. GetValue (Model,NULL))); }} name.remove (Name.length-1,1); Value.remove (Value.length-1,1); stringSQL =string. Format ("INSERT into {0} ({1}) VALUES ({2})", TableName, name.tostring (), value.tostring ()); returnSqlhelper.executenonquery (sqlhelper.getconnsting (), CommandType.Text, sql.tostring (), Parame.ToArray ()); } /// <summary> ///the record that the specified (Keyattribute) attribute points to by the model update/// </summary> /// <param name= "TableName" >the name of the table to update</param> /// <param name= "Model" >the model to update</param> /// <returns></returns> Public intUpdate (stringTableName, T Model) {propertyinfo[] propertys=Model.gettype (). GetProperties (); varstr =NewStringBuilder (); var where=NewStringBuilder (""); varParame =NewList<sqlparameter>(); foreach(varIteminchpropertys) { if(NULL!=item. GetCustomAttribute (typeof(Keyattribute))) { where. Append (item. Name). Append ("="). Append ("@"). Append (item. Name); Parame.add (NewSqlParameter ("@"+ Item. Name, item. GetValue (Model,NULL))); } Else{str. Append (item. Name). Append ("[email protected]"). Append (item. Name). Append (","); Parame.add (NewSqlParameter ("@"+ Item. Name, item. GetValue (Model,NULL))); }} str. Remove (str. Length-1,1); if(string. IsNullOrEmpty (where. ToString ()))Throw NewException ("Unable to update database without PrimaryKey found!"); stringsql =string. Format ("UPDATE {0} SET {1} WHERE {2}", TableName, str. ToString (),where. ToString ()); returnSqlhelper.executenonquery (sqlhelper.getconnsting (), CommandType.Text, SQL. ToString (), Parame.toarray ()); } }
Universal INSERT or update database through model