>Andy , 2023/06/04 # 在C#中實作Repository Pattern ## 建立IRepository介面 建立一個IReposutory.cs介面,並宣告為泛型<T>,接著宣告CRUD方法。 ```csharp namespace TrackSpending.EntityFrameworkCore.Repository { public interface ITSRepository<T> { Task<T> GetByIdAsync(int id); Task<IEnumerable<T>> GetAllAsync(); Task CreateAsync(T entity); Task UpdateAsync(T entity); Task DeleteAsync(T entity); } } ``` ## 實作IRepository 建立一個Repository.cs繼承IRepository.cs,注入DbContext後,實作CRUD方法。 ```csharp using Microsoft.EntityFrameworkCore; using TrackSpending.Model; namespace TrackSpending.EntityFrameworkCore.Repository { public class TSRepository<T> : ITSRepository<T> where T : class { private readonly TSDbContext _dbContext; private readonly DbSet<T> _dbSet; public TSRepository(TSDbContext dbContext) { _dbContext = dbContext; _dbSet = _dbContext.Set<T>(); } public async Task<T> GetByIdAsync(int id) { return await _dbSet.FindAsync(id); } public async Task<IEnumerable<T>> GetAllAsync() { return await _dbSet.ToListAsync(); } public async Task CreateAsync(T entity) { await _dbSet.AddAsync(entity); await _dbContext.SaveChangesAsync(); } public async Task DeleteAsync(T entity) { _dbSet.Remove(entity); await _dbContext.SaveChangesAsync(); } public async Task UpdateAsync(T entity) { _dbSet.Update(entity); await _dbContext.SaveChangesAsync(); } } } ``` ## 在Program.cs中註冊Repository服務,讓Service中可以注入使用 ```csharp //Repository builder.Services.AddScoped(typeof(ITSRepository<>),typeof(TSRepository<>)); ``` ## 注入Service中根據需求使用 ```csharp public class UserService : IUserService { private readonly ITSRepository<User> _tSRepository; public UserService(ITSRepository<User> tSRepository) { _tSRepository = tSRepository; } public async Task<UserCreateDto> CreateAsync(UserCreateDto input) { var data = new User(); data.Name = input.Name; await _tSRepository.CreateAsync(data); return input; } } ``` ## 啟動程式,打API測試 輸入"Nicole"測試一下。  成功後得到code:200  打開DB管理介面看一下。  ###### tags: `back-end`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up