Encapsulated TSQL Generic Update method in MVC LINQ

Source: Internet
Author: User

Take the TSQL out, do a package, apply all the tables, update there are two kinds, normal update and Count update

Look at the code: These two methods are written in the DAL in the data manipulation base class, only its subclasses can use it, so use protected as the limit

<summary>
Generic Update method
</summary>
<param name= "tableName" > table name </param>
<param name= "param" > Parameter list, odd for field, even for his previous odd number corresponding to the value, index 0 for the primary key to be updated, 1 primary key value </param>
protected virtual void Update (string tableName, params object[] param)
{
StringBuilder sbsql = new StringBuilder ();
list<object> listparasm = new list<object> ();
Listparasm.add (Param[0]);
Listparasm.add (param[1]);
int index = Listparasm.count;
Sbsql.appendformat ("UPDATE [{0}] SET", tableName);

if (index = = 0)
{
Return
}
Else
{
for (int i = 2; i < param. Count (); i + = 2)
{
if (Param[index + 1]. GetType () = = typeof (String))
Sbsql.appendformat ("{{{0}}} = ' {{1}} ',", index, index + 1);
Else
Sbsql.appendformat ("{{{0}}} = {{1}},", index, index + 1);
Listparasm.add (Param[index]);
Listparasm.add (Param[index + 1]);
index++;
index++;
}

Sbsql.remove (sbsql.length-1, 1);//Remove the last comma
}

Sbsql.append ("WHERE [{0}] = {1}");
Db. ExecuteCommand (Sbsql.tostring (), Listparasm.toarray ());
}

<summary>
Count Update
</summary>
<param name= "tableName" > table name </param>
<param name= "param" > Parameter list, index 0 primary Key name, 1 table key value, 2 for the field to be counted, 3 for increment </param>
protected virtual void Updateforcount (string tableName, params object[] param)
{
String sql = "Update [{0}] set [{3}]=[{3}]+{4} where [{1}]={2}";
list<object> listparasm = new list<object>
{
TableName,
Param[0],
PARAM[1],
PARAM[2],
PARAM[3],
};
Db. ExecuteCommand (String. Format (SQL, Listparasm.toarray ()));
}

Encapsulated TSQL Generic Update method in MVC LINQ

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.