I don't know if you are the same as me, and you will often face the following situations:
1. Users are often forced to insert, modify, or delete data manually to handle urgent cases. what bothers us most is not the SQL syntax, but the number of fields. A slightly larger table may involve dozens or more fields, if we have to manually write a line of insert code, errors will often occur, which is laborious and laborious! Very error-prone!
2. Now that you have data on hand, you need to urgently Add/update data in batches to synchronize old data on a server. The server does not have an open data import port.
...
These problems happen to me. I want to avoid them, so I want to use linqtosql + system. reflection. propertyinfo is a tedious task for me, with a relatively small workload, but I think it is necessary to share it.
First, we need to obtain the original data. This data comes from LINQ. These operations are dragging and dropping:
For example, I have an employee table:
List <employee> employees = datacontext. Employees. Where (C => C. ID> 10050). tolist ();
After obtaining the data source to be updated, the next step is to write them into SQL statements in batches. Here I directly output the data on the ASPX page.
Foreach (employee EMP in employees ){
Propertyinfo [] allproperty = EMP. GetType (). getproperties ();
String Part1 = string. Empty, Part2 = string. Empty; // required fields and values
For (INT I = 0; I <allproperty. length; I ++ ){
Object newvalue = allproperty [I]. getvalue (EMP, null );
String newname = allproperty [I]. Name;
Part1 + = newname + ",";
Part2 + = "'" + newvalue. tostring () + "',";
}
Response. write (string. format ("insert into employee ({0}) values ({1}); <br/>", part1.trim (','), part2.trim (',')));
}
Okay, it's almost over!
Now you don't have to worry about the number of fields and the corresponding value, but there is another small problem: If the value contains the ''' number, it will make an error, we recommend that you replace it.