Use dapper dapper use

Use dapper

 

I have not visited the project is to write database operations with EF, EF because in addition to the slower speed, but fast development efficiency, omitted a lot of sql wording, and can easily call the foreign key information, such as the collection, use EF succulent thing to write project. However, some project sites to consider running speed, then had to use other ORM framework, I used dapper, because of its fast results, and write sql very flexible, then take a look at some of the ways to use writing surface of dapper

1, connection statement

var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlDiagnosticsDb"].ConnectionString);

No need to consider whether the use of dapper conn connection, when performing self dapper open state is determined, if it can not open their open.

2、insert

string query = "INSERT INTO Book(Name)VALUES(@name)";
conn.Execute(query, book);

book class has a name attribute, so you can easy to write, of course, can be written as

string query = "INSERT INTO Book(Name)VALUES(@name)";
 conn.Execute(query,  new{@name=book.name});

3、update

string query = "UPDATE Book SET  Name=@name WHERE id =@id";
 conn.Execute(query, book);

4、 delete

string query = "DELETE FROM Book WHERE id = @id";
conn.Execute(query, book);
conn.Execute(query, new { id = id });

5、query

Copy the code
Query = String "the SELECT * the FROM Book"; 
// no parameter query returns a list with the same parameters and query parameter assignment before the law. 
 conn.Query <Book> (Query) .ToList (); 

 // return a single message 
 String Query = "Book the SELECT * the FROM @id the WHERE ID ="; 
 Book conn.Query = <Book> (Query, {ID = new new ID .}) SingleOrDefault ();  
Copy the code

6, the traditional sql in (1,2,3) with dapper so write

conn.Query<Users>("SELECT * FROM Users s WHERE s.id IN (@ids) ",new { ids = new int[]{1,2,3}})

conn.Query<Users>("SELECT * FROM Users s WHERE s.id IN (@ids) ",new { ids = IDs.ToArray()})

Because the security in dapper, not directly connected with the ground to be used sql parameterization,

7, bulk insert

conn.Execute(@"insert MyTable(colA, colB) values (@a, @b)", new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } })

It can also be written directly to a collection

conn.Execute("insert user(name) values(@name)",users)

Here the object is a collection of users in a user table, can be inserted once all the data sets to the data table.

8, multi-table queries

Copy the code
// When the query books, and find the corresponding book reviews, and there is a List. Implemented 1 - n query operation 
String Query = "Book the SELECT * B the LEFT the JOIN BookReview the FROM br = b.id the ON br.BookId @id the WHERE b.id ="; 
Book Lookup = null; 
// Query <TFirst, TSecond , T return> 
 var B = conn.Query <Book, BookReview, Book> (Query, 
  (Book, BookReview) => 
  { 
     // scanning a first record, and determining non-repeating non-empty 
    if (lookup == null || lookup ! .id = book.Id) 
      Lookup = book; 
    // book corresponding to the book reviews non-empty, the current is added in the book List book reviews, and finally remove the duplicate book. 
    IF (BookReview = null)! 
      lookup.Reviews.Add (BookReview ); 
     return Lookup; 
  .}, {ID = new new ID}) the Distinct () the SingleOrDefault ();. 
return B;
Copy the code

Multi-table joint inquiry is more trouble, now is not fully understood, look at a few examples

var sql =  @"select * from Posts p join Users u on u.Id = p.OwnerId Order by p.Id";
var data = conn.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;},splitOn:"id");
 

And Post class User class, they are foreign key, type conn.Query last parameter is returned Post, Post wherein there is a property Owner User object in the (post, user) => lamda value specified in the Owner,上边的代码中的splitOn是ID,运行时,会从查询结果所有字段列表的最后一个字段开始进行匹配,一直到找到Id这个字段(大小写忽略),找到的第一个ID字段匹配User类的ID属性,那么从ID到最后一个字段都属于User,ID以前的字段都被影射到Post 通过 (post, user) => { return post;},把两个类的实例解析出来。

9, three query, a table is associated with the primary key (single object), a table is a foreign key (set).

Copy the code
    public partial class UserInfo  
        {  
            public UserInfo()  
            {  
                this.Persion = new HashSet<Persion>();  
                this.MyTYC = new HashSet<MyTYC>();  
            }  
          
            public int id { get; set; }  
            public string name { get; set; }  
            public Nullable<System.DateTime> createTime { get; set; }  
            public Movies Movies { get; set; }  
            public virtual ICollection<MyTYC> MyTYC { get; set; }  
        }  
Copy the code
Copy the code
    public class Movies  
        {  
            public int ID { get; set; }  
            public string Title { get; set; }  
            public string ReleaseDate { get; set; }  
            public string Genre { get; set; }  
            public string Price { get; set; }  
            public UserInfo UserInfo { get; set; }  
      
        }  
Copy the code
Copy the code
    public partial class MyTYC  
        {  
            public int id { get; set; }  
            public string name { get; set; }  
      
        }  
Copy the code
string sql = @"select * from UserInfo u   
inner join [Movies].dbo.Movies m on u.id=m.ID   
inner join MyTYC t on u.id=t.id";  
            var data = conn.Query<UserInfo, Movies, MyTYC, UserInfo>(sql, (u, m, t) => { u.Movies = m; u.MyTYC.Add(t); return u; }); 

Note that the method of obtaining the objects and collections: u.Movies = m; u.MyTYC.Add (t);

10, multi-query results

Copy the code
var sql = @"select * from Customers where CustomerId = @id;
 select * from Orders where CustomerId = @id;
 select * from Returns where CustomerId = @id";

 using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
 {
        var customer = multi.Read<Customer>().Single();    
        var orders = multi.Read<Order>().ToList();
        var returns = multi.Read<Return>().ToList();
 }
Copy the code

another one

Copy the code
Program class   
    {   
  
        // create a connection object   
        protected static the SqlConnection the GetConnection ()   
        {   
            var = new new Connection the SqlConnection ( "the Data .; the Initial Cataog the Source = = the TestDB; the Integrated Security = True");   
            Connection.Open ();   
            return Connection;   
        }   
  
        static the Main void (String [] args)   
        {   
            // set test output result plurality   
            var sql = @ "INSERT INTO [   dbo] [Student] ([Name]) VALUES ( 'A1');. select @@ IDENTITY as A; 
                        INSERT INTO [dbo].[Student] ([Name]) VALUES ('B1'); select @@IDENTITY as A;  
                        the INTO the INSERT [the dbo] [Student] ([the Name]) the VALUES ( 'a C1');. @@ the IDENTITY AS SELECT A ";  
   
            // initialize the database connection  
            the using (= the GetConnection the SqlConnection Connection ())   
            {                   
                List <int> = IList new new List <int> ();   
                // execute the query, the result set acquired set   
                var = Multi connection.QueryMultiple (SQL);   
  
                // traverse the result set   
                while ( ! multi.IsConsumed)   
                {   
                    // read the current result set   
                    var = multi.Read result () ToList () [0] II.A;.   
                    ! IF (result = null)   
                    {   
                        IList.Add (Convert.ToInt32 (Result));  
                    }   
                }   
                // for (int I = 0; I <. 3; I ++)   
                // {  
                //    var result = multi.Read().ToList()[0].A;  
                //    if (result != null)  
                //    {  
                //        ilist.Add(Convert.ToInt32(result));  
                //    }  
                //}  
                foreach (var item in ilist)  
                {  
                    Console.WriteLine(item.ToString());  
                }  
            }  
            Console.ReadLine();  
        }  
    } 
Copy the code

11, if a code multiple database operations may be set to open the conn, when finally re-close,

such as:

 

Copy the code
conn.open()
conn.Query(.....
.....
for....
.....
conn.close()
Copy the code

 Transfer: https: //www.cnblogs.com/lunawzh/p/6607116.html

I have not visited the project is to write database operations with EF, EF because in addition to the slower speed, but fast development efficiency, omitted a lot of sql wording, and can easily call the foreign key information, such as the collection, use EF succulent thing to write project. However, some project sites to consider running speed, then had to use other ORM framework, I used dapper, because of its fast results, and write sql very flexible, then take a look at some of the ways to use writing surface of dapper

1, connection statement

var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlDiagnosticsDb"].ConnectionString);

No need to consider whether the use of dapper conn connection, when performing self dapper open state is determined, if it can not open their open.

2、insert

string query = "INSERT INTO Book(Name)VALUES(@name)";
conn.Execute(query, book);

book class has a name attribute, so you can easy to write, of course, can be written as

string query = "INSERT INTO Book(Name)VALUES(@name)";
 conn.Execute(query,  new{@name=book.name});

3、update

string query = "UPDATE Book SET  Name=@name WHERE id =@id";
 conn.Execute(query, book);

4、 delete

string query = "DELETE FROM Book WHERE id = @id";
conn.Execute(query, book);
conn.Execute(query, new { id = id });

5、query

Copy the code
Query = String "the SELECT * the FROM Book"; 
// no parameter query returns a list with the same parameters and query parameter assignment before the law. 
 conn.Query <Book> (Query) .ToList (); 

 // return a single message 
 String Query = "Book the SELECT * the FROM @id the WHERE ID ="; 
 Book conn.Query = <Book> (Query, {ID = new new ID .}) SingleOrDefault ();  
Copy the code

6, the traditional sql in (1,2,3) with dapper so write

conn.Query<Users>("SELECT * FROM Users s WHERE s.id IN (@ids) ",new { ids = new int[]{1,2,3}})

conn.Query<Users>("SELECT * FROM Users s WHERE s.id IN (@ids) ",new { ids = IDs.ToArray()})

Because the security in dapper, not directly connected with the ground to be used sql parameterization,

7, bulk insert

conn.Execute(@"insert MyTable(colA, colB) values (@a, @b)", new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } })

It can also be written directly to a collection

conn.Execute("insert user(name) values(@name)",users)

Here the object is a collection of users in a user table, can be inserted once all the data sets to the data table.

8, multi-table queries

Copy the code
// When the query books, and find the corresponding book reviews, and there is a List. Implemented 1 - n query operation 
String Query = "Book the SELECT * B the LEFT the JOIN BookReview the FROM br = b.id the ON br.BookId @id the WHERE b.id ="; 
Book Lookup = null; 
// Query <TFirst, TSecond , T return> 
 var B = conn.Query <Book, BookReview, Book> (Query, 
  (Book, BookReview) => 
  { 
     // scanning a first record, and determining non-repeating non-empty 
    if (lookup == null || lookup ! .id = book.Id) 
      Lookup = book; 
    // book corresponding to the book reviews non-empty, the current is added in the book List book reviews, and finally remove the duplicate book. 
    IF (BookReview = null)! 
      lookup.Reviews.Add (BookReview ); 
     return Lookup; 
  .}, {ID = new new ID}) the Distinct () the SingleOrDefault ();. 
return B;
Copy the code

Multi-table joint inquiry is more trouble, now is not fully understood, look at a few examples

var sql =  @"select * from Posts p join Users u on u.Id = p.OwnerId Order by p.Id";
var data = conn.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;},splitOn:"id");
 

And Post class User class, they are foreign key, type conn.Query last parameter is returned Post, Post wherein there is a property Owner User object in the (post, user) => lamda value specified in the Owner,上边的代码中的splitOn是ID,运行时,会从查询结果所有字段列表的最后一个字段开始进行匹配,一直到找到Id这个字段(大小写忽略),找到的第一个ID字段匹配User类的ID属性,那么从ID到最后一个字段都属于User,ID以前的字段都被影射到Post 通过 (post, user) => { return post;},把两个类的实例解析出来。

9, three query, a table is associated with the primary key (single object), a table is a foreign key (set).

Copy the code
    public partial class UserInfo  
        {  
            public UserInfo()  
            {  
                this.Persion = new HashSet<Persion>();  
                this.MyTYC = new HashSet<MyTYC>();  
            }  
          
            public int id { get; set; }  
            public string name { get; set; }  
            public Nullable<System.DateTime> createTime { get; set; }  
            public Movies Movies { get; set; }  
            public virtual ICollection<MyTYC> MyTYC { get; set; }  
        }  
Copy the code
Copy the code
    public class Movies  
        {  
            public int ID { get; set; }  
            public string Title { get; set; }  
            public string ReleaseDate { get; set; }  
            public string Genre { get; set; }  
            public string Price { get; set; }  
            public UserInfo UserInfo { get; set; }  
      
        }  
Copy the code
Copy the code
    public partial class MyTYC  
        {  
            public int id { get; set; }  
            public string name { get; set; }  
      
        }  
Copy the code
string sql = @"select * from UserInfo u   
inner join [Movies].dbo.Movies m on u.id=m.ID   
inner join MyTYC t on u.id=t.id";  
            var data = conn.Query<UserInfo, Movies, MyTYC, UserInfo>(sql, (u, m, t) => { u.Movies = m; u.MyTYC.Add(t); return u; }); 

Note that the method of obtaining the objects and collections: u.Movies = m; u.MyTYC.Add (t);

10, multi-query results

Copy the code
var sql = @"select * from Customers where CustomerId = @id;
 select * from Orders where CustomerId = @id;
 select * from Returns where CustomerId = @id";

 using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
 {
        var customer = multi.Read<Customer>().Single();    
        var orders = multi.Read<Order>().ToList();
        var returns = multi.Read<Return>().ToList();
 }
Copy the code

another one

Copy the code
Program class   
    {   
  
        // create a connection object   
        protected static the SqlConnection the GetConnection ()   
        {   
            var = new new Connection the SqlConnection ( "the Data .; the Initial Cataog the Source = = the TestDB; the Integrated Security = True");   
            Connection.Open ();   
            return Connection;   
        }   
  
        static the Main void (String [] args)   
        {   
            // set test output result plurality   
            var sql = @ "INSERT INTO [   
            // initialize the database connection  
                        INSERT INTO [dbo].[Student] ([Name]) VALUES ('B1'); select @@IDENTITY as A;  
                        . The INSERT the INTO [the dbo] [Student] ([the Name]) the VALUES ( 'a C1'); the IDENTITY AS SELECT @@ A ";   
  
            the using (= the GetConnection the SqlConnection Connection ())   
            {                   
                List <int> = IList new new List <int> ();   
                // execute the query, the result set acquired set   
                var = Multi connection.QueryMultiple (SQL);   
  
                // traverse the result set   
                the while (multi.IsConsumed!)   
                {   
                    // read the current result set   
                    var result = multi.Read () .ToList () [0] II.A;   
                    IF (Result = null!)   
                    {   
                        IList.Add (Convert.ToInt32 (Result));  
                    }   
                }   
                // for (int I = 0; I <. 3; I ++)   
                // {  
                //    var result = multi.Read().ToList()[0].A;  
                //    if (result != null)  
                //    {  
                //        ilist.Add(Convert.ToInt32(result));  
                //    }  
                //}  
                foreach (var item in ilist)  
                {  
                    Console.WriteLine(item.ToString());  
                }  
            }  
            Console.ReadLine();  
        }  
    } 
Copy the code

11, if a code multiple database operations may be set to open the conn, when finally re-close,

such as:

 

Copy the code
conn.open()
conn.Query(.....
.....
for....
.....
conn.close()
Copy the code

 Transfer: https: //www.cnblogs.com/lunawzh/p/6607116.html

Guess you like

Origin www.cnblogs.com/wangyu19900123/p/10984970.html