Recently in the company to look at the package code, access to the database is very convenient, we just define the model, we can access the database, of course, are encapsulated DLL, so I also tried to write a, now make a record.
The following is the definition of the attribute label, which is used primarily to obtain local property definitions and database definitions, as well as database field definitions:
public class Datamappingattribute:attribute { private string localname, DbName; private string type; Public Datamappingattribute (String A, string B, DbType type) { this.localname = A; This.dbname = b; This.type = "System." + type. ToString (); } public string LocalName { get {return localname;} } public string DbName {get {return DbName;}} public string DataType {get {return type;}} }
Following is the database access, generate the Entity model data list, mainly used in generic, reflection technology, Sir into a DataTable definition, and then populate with database data, traverse each row of data, according to the custom attributes, determine how the data and objects are one by one corresponding:
public class DataCommand {Private Const string connstr = "Data source=.;i Nitial catalog=xxx; User Id=sa; password=xxx; "; Public list<t> exe<t> (string cmdstr) {var reslist = new list<t> (); var dt = new DataTable (); /* Database field bound to DataTable */var type = typeof (T); var fieldlist = type. GetProperties (); foreach (Var filed in fieldlist) {var attributes = filed. GetCustomAttributes (typeof (Datamappingattribute), false); var ab = (Datamappingattribute) attributes[0]; Dt. Columns.Add (AB. Dbname,type.gettype (AB. DataType)); } using (var connection = new SqlConnection (CONNSTR)) {connection. Open (); var cmd = new SqlCommand {Connection = Connection}; Cmd.commandtext = Cmdstr; var dataAdapter = new SqlDataAdapter (cmd); DataadaptEr. Fill (DT); Connection. Close (); } foreach (DataRow row in dt. Rows) {var objt = activator.createinstance<t> (); foreach (Var filed in fieldlist) {var attributes = filed. GetCustomAttributes (typeof (Datamappingattribute), false); var tempname = ""; foreach (var attr in attributes) {var Attri = (datamappingattribute) attr; if (Attri. Localname.equals (filed. Name)) Tempname = Attri. DbName; } if (!filed. CanWrite | | String. Isnullorwhitespace (tempname)) continue; Filed. SetValue (Objt,row[tempname], NULL); } reslist.add (OBJT); } return reslist; }
Defining generic Access database classes