成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

一起聊聊 C# 中的工作單元模式

開發 前端
我們能夠確保多個數據庫操作的事務性,這在進行復雜的業務邏輯和數據操作時尤為重要。本文介紹了工作單元模式的基本概念和實現步驟,附帶具體的代碼示例,希望對你有所幫助。

工作單元(Unit of Work, UoW)模式是一種用于處理事務性工作的方法,特別適用于需要對數據庫進行多次操作時。它的主要目的是將多個數據庫操作封裝在一個事務中,確保所有操作能整體成功或者整體失敗,從而保證數據的一致性。

本文將詳細介紹如何在 C# 中實現工作單元模式,并提供完整的代碼注釋。

工作單元模式的關鍵概念

  1. 工作單元(Unit of Work):一個類,它封裝了一個業務事務的多個操作,并記錄對這些操作的更改。
  2. 倉儲(Repository):一個類,它管理實體的持久化,并通常與工作單元合作。
  3. 事務管理:確保多次數據庫操作要么全部成功,要么全部回滾。

實現步驟

下面是實現工作單元模式的步驟:

  1. 定義實體類。
  2. 定義倉儲接口和實現。
  3. 定義工作單元接口和實現。
  4. 使用工作單元及其倉儲。

1. 定義實體類

首先,我們定義一個簡單的實體類 Product。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace AppUnitWork
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

2. 定義倉儲接口和實現

接下來,定義各種實體的倉儲接口和實現。這里以 Product 為例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace AppUnitWork
{
    public interface IProductRepository
    {
        IEnumerable<Product> GetAll();
        Product GetById(int id);
        void Add(Product product);
        void Update(Product product);
        void Delete(int id);
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace AppUnitWork
{
    public class ProductRepository : IProductRepository
    {
        private readonly AppDbContext _context;


        public ProductRepository(AppDbContext context)
        {
            _context = context;
        }


        public IEnumerable<Product> GetAll() => _context.Products.ToList();


        public Product GetById(int id) => _context.Products.Find(id);


        public void Add(Product product)
        {
            _context.Products.Add(product);
        }


        public void Update(Product product)
        {
            _context.Products.Update(product);
        }


        public void Delete(int id)
        {
            var product = _context.Products.Find(id);
            if (product != null)
            {
                _context.Products.Remove(product);
            }
        }
    }
}

3. 定義工作單元接口和實現

定義工作單元以管理多個倉儲和事務。

public interface IUnitOfWork : IDisposable
{
    IProductRepository Products { get; }
    int Complete();
}


public class UnitOfWork : IUnitOfWork
{
    private readonly AppDbContext _context;
    public IProductRepository Products { get; private set; }


    public UnitOfWork(AppDbContext context, IProductRepository productRepository)
    {
        _context = context;
        Products = productRepository;
    }


    public int Complete()
    {
        return _context.SaveChanges();
    }


    public void Dispose()
    {
        _context.Dispose();
    }
}

4. 使用工作單元及其倉儲

示例調用代碼展示了如何使用工作單元和倉儲來實現多個數據庫操作的事務管理。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace AppUnitWork
{
    public class ProductService
    {
        private readonly IUnitOfWork _unitOfWork;


        public ProductService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }


        public void PerformProductOperations()
        {
            // 增加新產品
            var newProduct = new Product { Name = "New Product", Price = 99.99m };
            _unitOfWork.Products.Add(newProduct);
            _unitOfWork.Complete();
            Console.WriteLine("Added new product");


            // 更新現有產品
            var product = _unitOfWork.Products.GetById(1);
            if (product != null)
            {
                product.Price = 79.99m;
                _unitOfWork.Products.Update(product);
                _unitOfWork.Complete();
                Console.WriteLine("Updated existing product");
            }


            // 刪除產品
            _unitOfWork.Products.Delete(2);
            _unitOfWork.Complete();
            Console.WriteLine("Deleted product");
        }
    }
}

5. AppDbContext 類

確保你已經添加了 Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.InMemory 包。這可以通過 NuGet 包管理器或者在命令行中執行以下命令來完成:

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.InMemory


using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace AppUnitWork
{
    public class AppDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // 配置使用內存數據庫
            optionsBuilder.UseInMemoryDatabase("InMemoryDb");
        }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);


            // 通過種子數據來預填充內存數據庫
            modelBuilder.Entity<Product>().HasData(
                new Product { Id = 1, Name = "Product 1", Price = 10.00m },
                new Product { Id = 2, Name = "Product 2", Price = 20.00m }
            );
        }
    }
}

5. 調用

using Microsoft.Extensions.DependencyInjection;
using System;


namespace AppUnitWork
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 設置依賴注入
            var serviceProvider = new ServiceCollection()
                .AddDbContext<AppDbContext>()
                .AddScoped<IProductRepository, ProductRepository>()
                .AddScoped<IUnitOfWork, UnitOfWork>()
                .AddScoped<ProductService>()
                .BuildServiceProvider();


            using (var scope = serviceProvider.CreateScope())
            {
                var productService = scope.ServiceProvider.GetRequiredService<ProductService>();


                productService.PerformProductOperations();
                DisplayAllProducts(scope.ServiceProvider.GetRequiredService<IUnitOfWork>());
            }
        }


        static void DisplayAllProducts(IUnitOfWork unitOfWork)
        {
            var products = unitOfWork.Products.GetAll();
            foreach (var product in products)
            {
                Console.WriteLine($"Product Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");
            }
        }
    }
}

圖片圖片

總結

通過應用工作單元模式,我們能夠確保多個數據庫操作的事務性,這在進行復雜的業務邏輯和數據操作時尤為重要。本文介紹了工作單元模式的基本概念和實現步驟,附帶具體的代碼示例,希望對你有所幫助。


責任編輯:武曉燕 來源: 技術老小子
相關推薦

2024-11-28 09:57:50

C#事件發布器

2024-12-23 10:20:50

2025-01-09 07:54:03

2023-10-10 08:00:07

2025-02-13 09:32:12

C#重寫override

2024-07-10 08:31:59

C#特性代碼

2024-08-26 08:34:47

AES加密算法

2022-03-15 20:18:35

單元測試工具

2023-08-07 08:04:05

動態抽象工廠模式

2024-05-29 13:18:12

線程Thread?方式

2024-08-30 11:00:22

2022-12-06 08:12:11

Java關鍵字

2012-10-08 11:18:38

企業應用架構工作單元模式

2024-01-01 08:19:32

模式History前端

2023-10-26 08:38:43

SQL排名平分分區

2023-04-26 07:30:00

promptUI非結構化

2024-11-15 16:52:23

C#棧邊界棧基址

2022-10-08 00:00:05

SQL機制結構

2024-02-20 21:34:16

循環GolangGo

2021-08-27 07:06:10

IOJava抽象
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 精品在线视频播放 | 成人精品久久日伦片大全免费 | 精品无码三级在线观看视频 | 99久久99久久精品国产片果冰 | 亚洲一一在线 | 日韩精品视频在线 | 国产成人啪免费观看软件 | 中文字幕一区二区三区在线视频 | 国产美女在线观看 | 五月婷婷在线视频 | 国产免费让你躁在线视频 | 亚洲成人精品在线 | 99精品久久久久久中文字幕 | 国产激情视频网站 | 国产99久久久国产精品下药 | 欧美一区二区三区在线观看 | 欧美日韩国产欧美 | 欧美成人一区二区 | 国产精品亚洲综合 | 国产精品久久久久久一区二区三区 | 亚洲欧洲成人在线 | 一区在线播放 | www.日韩系列 | 动漫www.被爆羞羞av44 | 人人爽日日躁夜夜躁尤物 | 影音先锋男 | 久久久久成人精品 | 91国在线观看 | 啪啪av| 国产精品欧美一区二区三区不卡 | 青春草在线 | 日韩1区 | 日日草天天干 | 人人种亚洲 | 日韩有码一区二区三区 | 91精品国产综合久久久久久漫画 | 午夜小视频在线观看 | 国产1区在线 | 成人三区 | 毛片入口 | 欧美日韩精品久久久免费观看 |