First of all to build an entity class, note that the attributes of the entity class and data columns to correspond, otherwise it will error.
public class Animal {public string Name {get; set;} public int Age {get; set;} public int Weight {get; set;} public string Color {get; set;} }
Get the table structure to insert based on the entity class
Public Static stringGetproperty<t>(T t) {stringStr=String.Empty; StringBuilder SB=NewStringBuilder (); if(T = =NULL) { returnstr; } system.reflection.propertyinfo[] Properties=T.gettype (). GetProperties (); if(Properties. Length <=0) { returnstr; } foreach(System.Reflection.PropertyInfo Infoinchproperties) {sb. Append (string. Format ("@{0},", Info. Name)); } sb. Remove (sb.) Length-1,1); returnsb. ToString (); }
How to insert data:
Public intInsertbatch<t> (ienumerable<t>entities) {Type T=typeof(T); stringsql ="Insert into"+ T.name +"VALUES ("+classhelper.getproperty (entities. FirstOrDefault ()) +")"; using(System.Data.SqlClient.SqlConnection conn =NewSystem.Data.SqlClient.SqlConnection (ConnectionString)) {Conn. Open (); intRecords =0; using(vartrans =Conn. BeginTransaction ()) {Try{Records= Conn. Execute (SQL, entities, trans, -, CommandType.Text); } Catch(DataException ex) {trans. Rollback (); Throwex; } trans.commit (); } returnRecords; } }
C # uses transactions to bulk insert data