Dapper frame
1. Project references Dapper's nuget package;
2. Configure the Link class
usingSystem;usingSystem.Collections.Generic;usingSystem.Configuration;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedapper{ Public classDapperconn { Public Staticidbconnection getconnection () {stringConnStr = configurationmanager.appsettings["Conn"]; return NewSqlConnection (CONNSTR); } } }
3. Configure the Entity object for the corresponding table
Currently a user table and a user login log table for example:
User table
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedapper{ Public classUsermodel { PublicInt32 Id {Get;Set; } PublicString Key {Get;Set; } PublicString Value {Get;Set; } }}
User logon Log table
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedapper{ Public classUserloginlog { PublicInt32 Id {Get;Set; } PublicInt32 UserId {Get;Set; } PublicDateTime Createtime {Get;Set; } }}
4. Working with entities on the database
(contains basic: additions and deletions and transaction commit operations)
usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedapper{ Public classDB { Public intADD (Usermodel model) {using(varconn =dapperconn.getconnection ()) { stringsql ="Insert into User (key,value) Value (@Key, @Value)"; returnConn. Execute (SQL, model); } } Public intUpdate (Usermodel model) {using(varconn =dapperconn.getconnection ()) { stringsql ="update User Set [email protected],[email protected] where [email protected]"; returnConn. Execute (SQL, model); } } Public intDel (Usermodel model) {using(varconn =dapperconn.getconnection ()) { stringsql ="Delete from User where [email protected]"; returnConn. Execute (SQL, model); } } PublicUsermodel Getmodel () {using(varconn =dapperconn.getconnection ()) { varsql ="Select id,key,value from User"; returnConn. Queryfirstordefault<usermodel>(SQL); } } PublicIenumerable<usermodel>Getmodels () {using(varconn =dapperconn.getconnection ()) { varsql ="Select id,key,value from User"; returnConn. Query<usermodel>(SQL); } } Public voidImplementaffair (Usermodel Usermodel, Userloginlog userlogmodel) {using(varconn =dapperconn.getconnection ()) {IDbTransaction Tran=Conn. BeginTransaction (); Try { stringquery ="Update User set key= ' test ' where [email protected]";//Update a recordConn. Execute (query, Usermodel, Tran,NULL,NULL); Query="INSERT INTO Userloginlog (userid,createtime) value (@userId, @CreateTime)";//Delete a recordConn. Execute (query, Userlogmodel, Tran,NULL,NULL); //SubmitTran.commit (); } Catch(Exception ex) {//Commit Error//rolling back a transactionTran. Rollback (); } } } }}
. NET of Dapper Framework application