abp学习日志四(仓储)

仓储

“在领域层和数据映射层之间进行中介,使用类似集合的接口来操作领域对象.” (Martin Fowler).

个人理解仓储就是对实体进行CRUD操作的一套类,在充血模式中这套方法一般和实体放在一起,在贫血模式中一般会独立出来放到DAL层,也就是这里的仓储了。

提供方法

  • 提供 Insert 方法用于保存新实体.
  • 提供 Update 和 Delete 方法通过实体或实体id更新或删除实体.
  • 提供 Delete 方法使用条件表达式过滤删除多个实体.
  • 实现了 IQueryable, 所以你可以使用LINQ和扩展方法 FirstOrDefault, Where, OrderBy, ToList 等…
  • 所有方法都具有 sync(同步) 和 async(异步) 版本.

使用方式

private readonly IRepository<Person, Guid> _personRepository;

先看看我的使用用例,仓储的使用是在.Application项目中,也就是在Service层

using LY.Shop.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace LY.Shop
{
    public class ProductService : ShopAppService, IProductService
    {
        private readonly IRepository<Product> _productRepository;
        public ProductService(IRepository<Product> productRepository)
        {
            _productRepository = productRepository;
        }
		//添加
        public Task<ProductDto> AddAsync(ProductDto product)
        {
            var result = _productRepository.InsertAsync(new Product(GuidGenerator.Create()) { ProductPrice = 1, ProductUnit = "个", ProductName = product.Name }).ContinueWith(task =>
                         {
                             return product;
                         });
            return result;
        }
		//读取
        public Task<ProductDto> GetAsync()
        {
            var result = _productRepository.FirstOrDefault();
            return Task.FromResult(new ProductDto()
            {
                Name = result.ProductName
            }); ;
        }

        public Task<ProductDto> GetAuthorizedAsync()
        {
            return Task.FromResult(
                new ProductDto
                {
                    Name = "aaa"
                }
            );
        }
    }
}

so easy,既然这样,我们看看他都做了什么

源码目录
在这里插入图片描述

整个代码都是一IRepository作为基础接口进行实现的。

IReadOnlyBasicRepository.cs 做了一些读取的定义,Get, Find等
IBasicRepository.cs 做了一些插入 更新 删除等定义,
有兴趣的自己去github上看吧

自定义仓储

这个在实际业务开发过程中肯定是常用的,但是官网文档说是不常用,我就觉得奇怪了,难道是我对默认的仓储理解不够深入,遗漏了一些重要功能,先给自己留个一问吧。

public class PersonRepository : EfCoreRepository<MyDbContext, Person, Guid>, IPersonRepository
{
    public PersonRepository(IDbContextProvider<TestAppDbContext> dbContextProvider) 
        : base(dbContextProvider)
    {

    }

    public async Task<Person> FindByNameAsync(string name)
    {
        return await DbContext.Set<Person>()
            .Where(p => p.Name == name)
            .FirstOrDefaultAsync();
    }
}

官方给的例子挺好的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章