Easy to test, create console project, add SqlMapper.cs file to Project
I wrote all the content in the Program.cs file.
The first step is to prepare, define the connection string, open the database connection method, entity class, Query method.
//defining a connection string Static Private ReadOnly stringSqlConnection ="Data source=192.168.1.10;initial catalog=test; User Id=sa; Password=sa;"; //Open a database connection Static PublicSqlConnection OpenConnection () {SqlConnection connection=NewSqlConnection (SqlConnection); Connection. Open (); returnconnection; } //gets a collection of Sendmcpdetail objects. Static PublicIenumerable<sendmcpdetail>selectsendmcpdetails () {using(IDbConnection conn =OpenConnection ()) { Const stringquery ="SELECT * from Sendmcpdetail ORDER BY Sendmessageid Desc"; returnConn. Query<sendmcpdetail> (Query,NULL); } } //entity class Sendmcpdetail Public classSendmcpdetail { Public stringFormno {Get;Set; } Public stringSignno {Get;Set; } Public stringSignname {Get;Set; } Public stringSendpersonid {Get;Set; } Public stringSendmessageid {Get;Set; } PublicDateTime Creattime {Get;Set; } }
This simple data access has been set up, query data a sentence can be done
list<sendmcpdetail> allsendmcpdetail = Selectsendmcpdetails (). Tolist<sendmcpdetail> ();
Find out all the data and start to show, here I think the program automatically get the attributes of the entity class and get the value of the corresponding property after the query, using a simple reflection technology
foreach(Sendmcpdetail CatinchAllsendmcpdetail)//number of traversal queries{foreach(varIteminchCat. GetType (). GetProperties (BindingFlags.Instance |BindingFlags.Public| BindingFlags.NonPublic))//get all the properties in a class and traverse through reflection {Console.WriteLine (item. Name+":"+item. GetValue (CAT,NULL));//all properties in the class and read the value of the property } Console.WriteLine ("-------------------------------");}
The reflection is also the first time to use, the feeling is not very complex, but usually does not use very rarely, reflection can dynamically get the properties of the assembly, methods, and can access, modify property values and call methods.
Do more practice and get started.
A preliminary attempt to dapper simple practicality and reflection