AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

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

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

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

MNs28資訊網(wǎng)——每日最新資訊28at.com

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

示例1:多表關聯(lián)查詢

Dapper允許你輕松執(zhí)行多表關聯(lián)查詢。在這個示例中,我們將查詢兩個表,一個是Customers表,另一個是Orders表,并將它們關聯(lián)起來。MNs28資訊網(wǎng)——每日最新資訊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中使用事務。MNs28資訊網(wǎng)——每日最新資訊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允許你自定義數(shù)據(jù)類型到.NET類型的映射。在這個示例中,我們將使用TypeHandler來自定義Point類型的映射。MNs28資訊網(wǎng)——每日最新資訊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支持批量插入數(shù)據(jù),這對于大規(guī)模數(shù)據(jù)操作非常有用。在這個示例中,我們將演示如何批量插入多個產(chǎn)品記錄。MNs28資訊網(wǎng)——每日最新資訊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通常用于執(zhí)行SQL查詢,但你也可以執(zhí)行自定義的SQL語句,例如存儲過程或函數(shù)調(diào)用。在這個示例中,我們將演示如何執(zhí)行一個存儲過程。MNs28資訊網(wǎng)——每日最新資訊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語句執(zhí)行

你可以使用Dapper的Execute方法來執(zhí)行自定義的SQL語句,而不僅僅是查詢。在這個示例中,我們將演示如何執(zhí)行一個自定義的更新語句。MNs28資訊網(wǎng)——每日最新資訊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支持異步查詢,這對于高并發(fā)應用程序非常有用。在這個示例中,我們將演示如何使用異步方法執(zhí)行查詢。MNs28資訊網(wǎng)——每日最新資訊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特性來指定實體類與數(shù)據(jù)庫中不同表之間的映射關系。在這個示例中,我們將演示如何自定義表名。MNs28資訊網(wǎng)——每日最新資訊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:自定義參數(shù)前綴

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

using Dapper;using System;using System.Data;using System.Data.SqlClient;class Program{    static void Main()    {        SqlMapperExtensions.Configure("$$$"); // 設置參數(shù)前綴為 $$$        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來執(zhí)行分頁查詢。在這個示例中,我們將演示如何執(zhí)行分頁查詢。MNs28資訊網(wǎng)——每日最新資訊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的一些高級功能,包括多表關聯(lián)查詢、事務處理、自定義類型映射、批量插入、自定義SQL語句、異步查詢、自定義表名、自定義參數(shù)前綴和查詢分頁。通過這些示例,你可以更好地了解如何在實際應用中充分利用Dapper來簡化數(shù)據(jù)訪問任務。MNs28資訊網(wǎng)——每日最新資訊28at.com

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

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

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

下一篇: 文件系統(tǒng)那些事兒,你學會了嗎?

標簽:
  • 熱門焦點
  • 一加Ace2 Pro真機揭曉 鈦空灰配色質(zhì)感拉滿

    終于,在經(jīng)過了幾波預熱之后,一加Ace2 Pro的外觀真機圖在網(wǎng)上出現(xiàn)了。還是博主數(shù)碼閑聊站曝光的,這次的外觀設計還是延續(xù)了一加11的方案,只是細節(jié)上有了調(diào)整,例如新加入了鈦空灰
  • 俄羅斯:將審查iPhone等外國公司設備 保數(shù)據(jù)安全

    iPhone和特斯拉都屬于在各自領域領頭羊的品牌,推出的產(chǎn)品也也都是數(shù)一數(shù)二的,但對于一些國家而言,它們的產(chǎn)品可靠性和安全性還是在限制范圍內(nèi)。近日,俄羅斯聯(lián)邦通信、信息技術
  • Redmi Buds 4開箱簡評:才199還有降噪 可以無腦入

    在上個月舉辦的Redmi Note11T Pro系列新機發(fā)布會上,除了兩款手機新品之外,Redmi還帶來了兩款TWS真無線藍牙耳機產(chǎn)品,Redmi Buds 4和Redmi Buds 4 Pro,此前我們在Redmi Note11T
  • 石頭自清潔掃拖機器人G10S評測:多年黑科技集大成之作 懶人終極福音

    科技圈經(jīng)常能看到一個詞叫“縫合怪”,用來形容那些把好多功能或者外觀結合在一起的產(chǎn)品,通常這樣的詞是貶義詞,但如果真的是產(chǎn)品縫合的好、縫合的實用的話,那它就成了中性詞,今
  • 6月安卓手機性能榜:vivo/iQOO霸占旗艦排行榜前三

    2023年上半年已經(jīng)正式過去了,我們也迎來了安兔兔V10版本,在新的驍龍8Gen3和天璣9300發(fā)布之前,性能榜的榜單大體會以驍龍8Gen2和天璣9200+為主,至于那顆3.36GHz的驍龍8Gen2領先
  • 一篇文章帶你了解 CSS 屬性選擇器

    屬性選擇器對帶有指定屬性的 HTML 元素設置樣式??梢詾閾碛兄付▽傩缘?HTML 元素設置樣式,而不僅限于 class 和 id 屬性。一、了解屬性選擇器CSS屬性選擇器提供了一種簡單而
  • 零售大模型“干中學”,攀爬數(shù)字化珠峰

    文/侯煜編輯/cc來源/華爾街科技眼對于絕大多數(shù)登山愛好者而言,攀爬珠穆朗瑪峰可謂終極目標。攀登珠峰的商業(yè)路線有兩條,一是尼泊爾境內(nèi)的南坡路線,一是中國境內(nèi)的北坡路線。相
  • 8月見!小米MIX Fold 3獲得3C認證:支持67W快充

    這段時間以來,包括三星、一加、榮耀等等有不少品牌旗下的最新折疊屏旗艦都得到了不少爆料,而小米新一代折疊屏旗艦——小米MIX Fold 3此前也屢屢被傳
  • 電博會與軟博會實現(xiàn)"線下+云端"的雙線融合

    在本次“電博會”與“軟博會”雙展會利好條件的加持下,既可以發(fā)揮展會拉動人流、信息流、資金流實現(xiàn)快速交互流動的作用,繼而推動區(qū)域經(jīng)濟良性發(fā)展;又可以聚
Top