輕量級ORM架構 【Dapper】 的使用

來源:互聯網
上載者:User

標籤:net   keep   DApp   https   multi   list()   cti   分享   com   

ORM是什嗎?

從字面理解,O是Object,對象;R是Relation,關係;M是Mapping,映射。所以,用一句話概括就是:ORM是一種對象關係映射的技術

 

Dapper 是.NET下的一種ORM架構。

Dapper的安裝

使用NuGet安裝
開啟visual studio的項目,依次點擊工具NuGet包管理器管理解決方案的NuGet程式包;再點擊瀏覽搜尋dapper點擊搜尋結果中的Dapper勾選項目選擇安裝;

解決方案管理器中點擊項目查看引用,如果有Dapper,說明安裝成功。

 

Dapper的基本用法

首先,我們在Model層寫一個Person類,他有ID,Name,Remark。

同樣我們在資料庫也有一個Person表,包含id,name,remark三個欄位,其中id是主鍵自增。

而後我們在DAL層寫一個PersonDB類,提供對Person的基本訪問。connectionString是資料庫連接字串,由設定檔讀取。

插入操作

將一個對象person插入資料庫。插入代碼文本如下。@Name的意思是自動將person裡的Name值綁定上去。

public static int Insert(Person person){     using (IDbConnection connection = new SqlConnection(connectionString))    {        return connection.Execute("insert into Person(Name,Remark)                                      values(@Name,@Remark)", person);    }}

批量插入:

/// <summary>/// 批量插入Person資料,返回影響行數/// </summary>/// <param name="persons"></param>/// <returns>影響行數</returns>public static int Insert(List<Person> persons){    using (IDbConnection connection = new SqlConnection(connectionString))    {        return connection.Execute("insert into Person(Name,Remark) values(@Name,@Remark)", persons);    }}
刪除操作:
public static int Delete(Person person){    using (IDbConnection connection = new SqlConnection(connectionString))    {        return connection.Execute("delete from Person where [email protected]", person);    }}public static int Delete(List<Person> persons){    using (IDbConnection connection = new SqlConnection(connectionString))    {        return connection.Execute("delete from Person where [email protected]", persons);    }}
修改操作:
public static int Update(Person person){    using (IDbConnection connection = new SqlConnection(connectionString))    {        return connection.Execute("update Person set [email protected] where [email protected]", person);    }}public static int Update(List<Person> persons){    using (IDbConnection connection = new SqlConnection(connectionString))    {        return connection.Execute("update Person set [email protected] where [email protected]", persons);    }}
查詢操作:
/// <summary>/// 無參查詢所有資料/// </summary>/// <returns></returns>public static List<Person> Query(){    using (IDbConnection connection = new SqlConnection(connectionString))    {        return connection.Query<Person>("select * from Person").ToList();    }}/// <summary>/// 查詢指定資料/// </summary>/// <param name="person"></param>/// <returns></returns>public static Person Query(Person person){    using (IDbConnection connection = new SqlConnection(connectionString))    {        return connection.Query<Person>("select * from Person where [email protected]", person).SingleOrDefault();    }}

 

Dapper的複雜操作查詢的In操作:
/// <summary>/// In操作/// </summary>public static List<Person> QueryIn(){    using (IDbConnection connection = new SqlConnection(connectionString))    {        var sql = "select * from Person where id in @ids";        //參數類型是Array的時候,dappper會自動將其轉化        return connection.Query<Person>(sql, new { ids = new int[2] { 1, 2 }, }).ToList();    }}public static List<Person> QueryIn(int[] ids){    using (IDbConnection connection = new SqlConnection(connectionString))    {        var sql = "select * from Person where id in @ids";        //參數類型是Array的時候,dappper會自動將其轉化        return connection.Query<Person>(sql, new { ids }).ToList();    }}
多語句操作

為此我們引入以下Book類,同樣在資料庫裡設定這個表。

public class Book{    public int ID { get; set; }    public int PersonID { get; set; }    public string BookName { get; set; }}
/// <summary>/// 多語句操作/// </summary>public static void QueryMultiple(){    using (IDbConnection connection = new SqlConnection(connectionString))    {        var sql = "select * from Person; select * from Book";        var multiReader = connection.QueryMultiple(sql);        var personList = multiReader.Read<Person>();        var bookList = multiReader.Read<Book>();        multiReader.Dispose();    }}
Join操作

我們是物件導向編程,所以一個對象裡面會有許多其他子物件,這個子物件裡面又有其自己的子物件,這種關係在資料庫裡的表示就是外鍵。
比如我們有一本書book,它有主人person,book是一個對象,主人又是一個對象。

public class BookWithPerson{    public int ID { get; set; }    public Person Pers { get; set; }    public string BookName { get; set; }}
我們自然想要一個方法把資料庫裡複雜的外鍵關係轉成我們需要的對象BookWithPerson,所有我們需要的資訊都存在裡面,取資料的時候只要找這個對象取資料就行了,比如我們需要一本書的主人的姓名,我們只需要bookWithPerson.Pers.Name。如果是一對多的關係我們用數組,如果是多對多我們加一層mapping。
現在我們想根據書的ID查詢書的資訊,包括主人資訊。
public static BookWithPerson QueryJoin(Book book){    using (IDbConnection connection = new SqlConnection(connectionString))    {        var sql = @"select b.id,b.bookName,p.id,p.name,p.remark                        from Person as p                        join Book as b                        on p.id = b.personId                        where b.id = @id;";        var result = connection.Query<BookWithPerson, Person, BookWithPerson>(sql,          (bookWithPerson, person) =>          {              bookWithPerson.Pers = person;              return bookWithPerson;          },        book);        //splitOn: "bookName");        return (BookWithPerson)result;    }}
其中,Query的三個泛型參數分別是 委託回調類型1委託回調類型2傳回型別。形參的三個參數分別是 sql語句map委託對象參數。所以整句的意思是先根據sql語句查詢;同時把查詢的person資訊賦值給bookWithPerson.Pers,並且返回bookWithPerson;book是對象參數,提供參數綁定的值。
最終整個方法返回BookWithPerson,這樣我們所需要的所有資訊就有了。



 ***************************** *** Keep learning and growing. *** *****************************

輕量級ORM架構 【Dapper】 的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.