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

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

開(kāi)發(fā) 前端
我們能夠確保多個(gè)數(shù)據(jù)庫(kù)操作的事務(wù)性,這在進(jìn)行復(fù)雜的業(yè)務(wù)邏輯和數(shù)據(jù)操作時(shí)尤為重要。本文介紹了工作單元模式的基本概念和實(shí)現(xiàn)步驟,附帶具體的代碼示例,希望對(duì)你有所幫助。

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

本文將詳細(xì)介紹如何在 C# 中實(shí)現(xiàn)工作單元模式,并提供完整的代碼注釋。

工作單元模式的關(guān)鍵概念

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

實(shí)現(xiàn)步驟

下面是實(shí)現(xiàn)工作單元模式的步驟:

  1. 定義實(shí)體類。
  2. 定義倉(cāng)儲(chǔ)接口和實(shí)現(xiàn)。
  3. 定義工作單元接口和實(shí)現(xiàn)。
  4. 使用工作單元及其倉(cāng)儲(chǔ)。

1. 定義實(shí)體類

首先,我們定義一個(gè)簡(jiǎn)單的實(shí)體類 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. 定義倉(cāng)儲(chǔ)接口和實(shí)現(xiàn)

接下來(lái),定義各種實(shí)體的倉(cāng)儲(chǔ)接口和實(shí)現(xiàn)。這里以 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. 定義工作單元接口和實(shí)現(xiàn)

定義工作單元以管理多個(gè)倉(cāng)儲(chǔ)和事務(wù)。

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. 使用工作單元及其倉(cāng)儲(chǔ)

示例調(diào)用代碼展示了如何使用工作單元和倉(cāng)儲(chǔ)來(lái)實(shí)現(xiàn)多個(gè)數(shù)據(jù)庫(kù)操作的事務(wù)管理。

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()
        {
            // 增加新產(chǎn)品
            var newProduct = new Product { Name = "New Product", Price = 99.99m };
            _unitOfWork.Products.Add(newProduct);
            _unitOfWork.Complete();
            Console.WriteLine("Added new product");


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


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

5. AppDbContext 類

確保你已經(jīng)添加了 Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.InMemory 包。這可以通過(guò) NuGet 包管理器或者在命令行中執(zhí)行以下命令來(lái)完成:

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)
        {
            // 配置使用內(nèi)存數(shù)據(jù)庫(kù)
            optionsBuilder.UseInMemoryDatabase("InMemoryDb");
        }


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


            // 通過(guò)種子數(shù)據(jù)來(lái)預(yù)填充內(nèi)存數(shù)據(jù)庫(kù)
            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. 調(diào)用

using Microsoft.Extensions.DependencyInjection;
using System;


namespace AppUnitWork
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 設(shè)置依賴注入
            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}");
            }
        }
    }
}

圖片圖片

總結(jié)

通過(guò)應(yīng)用工作單元模式,我們能夠確保多個(gè)數(shù)據(jù)庫(kù)操作的事務(wù)性,這在進(jìn)行復(fù)雜的業(yè)務(wù)邏輯和數(shù)據(jù)操作時(shí)尤為重要。本文介紹了工作單元模式的基本概念和實(shí)現(xiàn)步驟,附帶具體的代碼示例,希望對(duì)你有所幫助。


責(zé)任編輯:武曉燕 來(lái)源: 技術(shù)老小子
相關(guān)推薦

2024-11-28 09:57:50

C#事件發(fā)布器

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

單元測(cè)試工具

2023-08-07 08:04:05

動(dòng)態(tài)抽象工廠模式

2024-05-29 13:18:12

線程Thread?方式

2022-12-06 08:12:11

Java關(guān)鍵字

2024-08-30 11:00:22

2012-10-08 11:18:38

企業(yè)應(yīng)用架構(gòu)工作單元模式

2024-01-01 08:19:32

模式History前端

2023-10-26 08:38:43

SQL排名平分分區(qū)

2022-10-08 00:00:05

SQL機(jī)制結(jié)構(gòu)

2023-04-26 07:30:00

promptUI非結(jié)構(gòu)化

2024-11-15 16:52:23

C#棧邊界棧基址

2023-08-10 08:28:46

網(wǎng)絡(luò)編程通信

2023-08-04 08:20:56

DockerfileDocker工具
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 欧美人妖网站 | 成人性生交大片免费看r链接 | 在线视频成人 | 国产在线拍偷自揄拍视频 | 欧美一区二区三区四区视频 | 四虎最新视频 | 国产精品亚洲第一区在线暖暖韩国 | 成人福利片 | 亚洲免费在线观看 | 一本一道久久a久久精品蜜桃 | 成人国产在线观看 | а天堂中文最新一区二区三区 | 亚洲成人在线免费 | 亚洲欧美另类在线 | 亚洲毛片网站 | 亚洲国产精品va在线看黑人 | 亚洲国产网 | 久久久久久九九九九 | 国产精品视频久久 | 欧美一区二区在线看 | 欧美一区二区三区国产精品 | 久久精品久久久久久 | 国产成人精品一区 | 国产日韩av一区二区 | 日本不卡一区二区三区在线观看 | 国产亚洲一区二区三区在线观看 | av免费入口 | 国产一区二区 | 黄色免费在线观看网站 | 久久久久一区二区三区四区 | 亚洲日韩中文字幕一区 | 在线免费观看成人 | av在线免费观看网站 | 蜜臀久久| 国产欧美精品区一区二区三区 | 网黄在线 | 中文字幕av一区 | 337p日本欧洲亚洲大胆精蜜臀 | 亚洲电影一区 | 一区二区在线 | 欧美久久一区 |