日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

.NET輕量級ORM框架Dapper.NET的高級應用實例詳解

來源: 責編: 時間:2024-02-06 10:11:45 323觀看
導讀Dapper是一個輕量級的ORM(對象關系映射)庫,用于.NET應用程序與數據庫之間的數據訪問。它允許你使用SQL查詢來執行數據庫操作,而不需要復雜的映射配置。在這篇文章中,我將為您提供Dapper的高級應用功能示例,每個示例都有源代

loT28資訊網——每日最新資訊28at.com

Dapper是一個輕量級的ORM(對象關系映射)庫,用于.NET應用程序與數據庫之間的數據訪問。它允許你使用SQL查詢來執行數據庫操作,而不需要復雜的映射配置。在這篇文章中,我將為您提供Dapper的高級應用功能示例,每個示例都有源代碼和注釋。這些示例將涵蓋Dapper的一些高級功能,以幫助你更好地理解如何在實際應用中使用它。loT28資訊網——每日最新資訊28at.com

示例1:多表關聯查詢

Dapper允許你輕松執行多表關聯查詢。在這個示例中,我們將查詢兩個表,一個是Customers表,另一個是Orders表,并將它們關聯起來。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;using System.Linq;public class Customer{    public int CustomerId { get; set; }    public string CustomerName { get; set; }}public class Order{    public int OrderId { get; set; }    public int CustomerId { get; set; }    public decimal TotalAmount { get; set; }}class Program{    static void Main()    {        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        string query = "SELECT c.CustomerId, c.CustomerName, o.OrderId, o.TotalAmount " +                       "FROM Customers c " +                       "JOIN Orders o ON c.CustomerId = o.CustomerId";        var result = dbConnection.Query<Customer, Order, Customer>(            query,            (customer, order) =>            {                customer.Orders = order;                return customer;            },            splitOn: "OrderId"        );        foreach (var customer in result)        {            Console.WriteLine($"Customer ID: {customer.CustomerId}, Name: {customer.CustomerName}");            Console.WriteLine($"Order ID: {customer.Orders.OrderId}, Total Amount: {customer.Orders.TotalAmount}");            Console.WriteLine();        }    }}

示例2:事務處理

Dapper允許你使用事務來確保一組操作要么全部成功,要么全部失敗。在這個示例中,我們將演示如何在Dapper中使用事務。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{    static void Main()    {        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        dbConnection.Open();        using var transaction = dbConnection.BeginTransaction();        try        {            string insertQuery = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)";            string updateQuery = "UPDATE Customers SET CustomerName = @CustomerName WHERE CustomerId = @CustomerId";            var product = new { Name = "ProductX", Price = 19.99 };            var customer = new { CustomerName = "NewName", CustomerId = 1 };            dbConnection.Execute(insertQuery, product, transaction: transaction);            dbConnection.Execute(updateQuery, customer, transaction: transaction);            // Commit the transaction if all operations are successful            transaction.Commit();            Console.WriteLine("Transaction committed.");        }        catch (Exception ex)        {            // Rollback the transaction if any operation fails            transaction.Rollback();            Console.WriteLine("Transaction rolled back. Error: " + ex.Message);        }    }}

示例3:自定義類型映射

Dapper允許你自定義數據類型到.NET類型的映射。在這個示例中,我們將使用TypeHandler來自定義Point類型的映射。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;using Npgsql;using NpgsqlTypes;public class Point{    public double X { get; set; }    public double Y { get; set; }}public class PointTypeHandler : SqlMapper.TypeHandler<Point>{    public override void SetValue(IDbDataParameter parameter, Point value)    {        parameter.Value = $"({value.X},{value.Y})";        parameter.DbType = DbType.String;    }    public override Point Parse(object value)    {        if (value is string strValue)        {            var parts = strValue.Trim('(', ')').Split(',');            if (parts.Length == 2 && double.TryParse(parts[0], out double x) && double.TryParse(parts[1], out double y))            {                return new Point { X = x, Y = y };            }        }        return null;    }}class Program{    static void Main()    {        SqlMapper.AddTypeHandler(new PointTypeHandler());        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new NpgsqlConnection(connectionString);        string query = "SELECT PointColumn FROM MyTable WHERE Id = @Id";        var result = dbConnection.Query<Point>(query, new { Id = 1 }).FirstOrDefault();        if (result != null)        {            Console.WriteLine($"X: {result.X}, Y: {result.Y}");        }        else        {            Console.WriteLine("Point not found.");        }    }}

示例4:批量插入

Dapper支持批量插入數據,這對于大規模數據操作非常有用。在這個示例中,我們將演示如何批量插入多個產品記錄。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;public class Product{    public string Name { get; set; }    public decimal Price { get; set; }}class Program{    static void Main()    {        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        dbConnection.Open();        var products = new List<Product>        {            new Product { Name = "ProductA", Price = 10.99m },            new Product { Name = "ProductB", Price = 15.99m },            new Product { Name = "ProductC", Price = 20.99m }        };        string insertQuery = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)";        int rowsAffected = dbConnection.Execute(insertQuery, products);        Console.WriteLine($"{rowsAffected} rows inserted.");    }}

示例5:自定義SQL語句

雖然Dapper通常用于執行SQL查詢,但你也可以執行自定義的SQL語句,例如存儲過程或函數調用。在這個示例中,我們將演示如何執行一個存儲過程。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{    static void Main()    {        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        string storedProcedure = "MyStoredProcedure";        var parameters = new DynamicParameters();        parameters.Add("Param1", 123);        parameters.Add("Param2", "TestValue", DbType.String, ParameterDirection.Input, 50);        var result = dbConnection.Query<int>(storedProcedure, parameters, commandType: CommandType.StoredProcedure).FirstOrDefault();        Console.WriteLine($"Stored procedure result: {result}");    }}

示例6:自定義SQL語句執行

你可以使用Dapper的Execute方法來執行自定義的SQL語句,而不僅僅是查詢。在這個示例中,我們將演示如何執行一個自定義的更新語句。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{    static void Main()    {        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        string updateStatement = "UPDATE Customers SET CustomerName = @NewName WHERE CustomerId = @CustomerId";        var parameters = new { NewName = "NewName", CustomerId = 1 };        int rowsAffected = dbConnection.Execute(updateStatement, parameters);        Console.WriteLine($"{rowsAffected} rows updated.");    }}

示例7:異步查詢

Dapper支持異步查詢,這對于高并發應用程序非常有用。在這個示例中,我們將演示如何使用異步方法執行查詢。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;using System.Threading.Tasks;class Program{    static async Task Main()    {        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        string query = "SELECT * FROM Products";        var products = await dbConnection.QueryAsync<Product>(query);        foreach (var product in products)        {            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");        }    }}

示例8:自定義表名

你可以使用Dapper的Table特性來指定實體類與數據庫中不同表之間的映射關系。在這個示例中,我們將演示如何自定義表名。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;[Table("MyCustomTableName")]public class CustomTable{    public int Id { get; set; }    public string Name { get; set; }}class Program{    static void Main()    {        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        string query = "SELECT * FROM MyCustomTableName";        var result = dbConnection.Query<CustomTable>(query);        foreach (var item in result)        {            Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");        }    }}

示例9:自定義參數前綴

Dapper默認使用@作為參數前綴,但你可以自定義參數前綴。在這個示例中,我們將演示如何自定義參數前綴為$。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{    static void Main()    {        SqlMapperExtensions.Configure("$$$"); // 設置參數前綴為 $$$        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        string query = "SELECT * FROM Products WHERE Name = $$$productName";        var result = dbConnection.Query<Product>(query, new { productName = "ProductA" });        foreach (var product in result)        {            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");        }    }}

示例10:查詢分頁

Dapper使分頁查詢變得容易,你可以使用LIMITOFFSET來執行分頁查詢。在這個示例中,我們將演示如何執行分頁查詢。loT28資訊網——每日最新資訊28at.com

using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{    static void Main()    {        string connectionString = "YourConnectionStringHere";        using IDbConnection dbConnection = new SqlConnection(connectionString);        int pageSize = 10;        int pageNumber = 2;        string query = "SELECT * FROM Products ORDER BY ProductId OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY";        var result = dbConnection.Query<Product>(query, new { Offset = (pageNumber - 1) * pageSize, PageSize = pageSize });        foreach (var product in result)        {            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");        }    }}

這些示例演示了Dapper的一些高級功能,包括多表關聯查詢、事務處理、自定義類型映射、批量插入、自定義SQL語句、異步查詢、自定義表名、自定義參數前綴和查詢分頁。通過這些示例,你可以更好地了解如何在實際應用中充分利用Dapper來簡化數據訪問任務。loT28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-74665-0.html.NET輕量級ORM框架Dapper.NET的高級應用實例詳解

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 學到了!Figma 原來是這樣表示矩形的

下一篇: 文件系統那些事兒,你學會了嗎?

標簽:
  • 熱門焦點
  • K60至尊版狂暴引擎2.0加持:超177萬跑分斬獲性能第一

    Redmi的后性能時代戰略發布會今天下午如期舉辦,在本次發布會上,Redmi公布了多項關于和聯發科的深度合作,以及新機K60 Ultra在軟件和硬件方面的特性,例如:“K60 至尊版,雙芯旗艦
  • 一年經驗在二線城市面試后端的經驗分享

    忠告這篇文章只適合2年內工作經驗、甚至沒有工作經驗的朋友閱讀。如果你是2年以上工作經驗,請果斷劃走,對你沒啥幫助~主人公這篇文章內容來自 「升職加薪」星球星友 的投稿,坐
  • 19個 JavaScript 單行代碼技巧,讓你看起來像個專業人士

    今天這篇文章跟大家分享18個JS單行代碼,你只需花幾分鐘時間,即可幫助您了解一些您可能不知道的 JS 知識,如果您已經知道了,就當作復習一下,古人云,溫故而知新嘛。現在,我們就開始今
  • 虛擬鍵盤 API 的妙用

    你是否在遇到過這樣的問題:移動設備上有一個固定元素,當激活虛擬鍵盤時,該元素被隱藏在了鍵盤下方?多年來,這一直是 Web 上的默認行為,在本文中,我們將探討這個問題、為什么會發生
  • 本地生活這塊肥肉,拼多多也想吃一口

    出品/壹覽商業 作者/李彥編輯/木魚拼多多也看上本地生活這塊蛋糕了。近期,拼多多在App首頁&ldquo;充值中心&rdquo;入口上線了本機生活界面。壹覽商業發現,該界面目前主要
  • 得物寵物生意「狂飆」,發力“它經濟”

    作者|花花小萌主近日,得物宣布正式上線寵物鑒別,通過得物App內的&ldquo;在線鑒別&rdquo;,可找到鑒別寵物的選項。通過上傳自家寵物的部位細節,就能收獲擁有專業資質認證的得物鑒
  • iQOO Neo8系列新品發布會

    旗艦雙芯 更強更Pro
  • AI藝術欣賞體驗會在上海梅賽德斯奔馳中心音樂俱樂部上演

    光影交錯的鏡像世界,虛實幻化的視覺奇觀,虛擬偶像與真人共同主持,這些場景都出現在2019世界人工智能大會的舞臺上。8月29日至31日,“AI藝術欣賞體驗會”在上海
  • 上海舉辦人工智能大會活動,建設人工智能新高地

    人工智能大會在上海浦江兩岸隆重拉開帷幕,人工智能新技術、新產品、新應用、新理念集中亮相。8月30日晚,作為大會的特色活動之一的上海人工智能發展盛典人工
Top 主站蜘蛛池模板: 临澧县| 商城县| 翁牛特旗| 靖宇县| 万盛区| 沭阳县| 北川| 双峰县| 蒙城县| 周宁县| 板桥市| 北辰区| 桑植县| 化隆| 怀安县| 新乡县| 神木县| 湘潭县| 福海县| 营口市| 来安县| 龙门县| 大英县| 土默特右旗| 临夏市| 武乡县| 合肥市| 奉化市| 永泰县| 新疆| 民勤县| 化德县| 怀宁县| 子洲县| 安化县| 石家庄市| 荆门市| 明水县| 边坝县| 韶关市| 陕西省|