0

对于组织单位,我们使用下面的代码来获取组织单位中的实体,包括其子组织单位。是否合理以及如何扩展IRepository以将此功能添加到所有实体?

public virtual List<Product> GetProductsInOuIncludingChildren(long organizationUnitId)
{
    var code = _organizationUnitRepository.Get(organizationUnitId).Code;

    var query =
        from product in _productRepository.GetAll()
        join organizationUnit in _organizationUnitRepository.GetAll() on product.OrganizationUnitId equals organizationUnit.Id
        where organizationUnit.Code.StartsWith(code)
        select product;

    return query.ToList();
}
4

2 回答 2

2

首先,继承IMustHaveOrganizationUnit

public class Product : Entity, IMustHaveOrganizationUnit
{
    public long OrganizationUnitId { get; set; }
}

然后定义扩展方法:

public static class RepositoryExtensions
{
    public static List<TEntity> GetAllInOuIncludingChildren<TEntity, TPrimaryKey>(
        this IRepository<TEntity, TPrimaryKey> repository,
        long organizationUnitId
    )
        where TEntity : class, IEntity<TPrimaryKey>, IMustHaveOrganizationUnit
    {
        using (var organizationUnitRepository = repository.GetIocResolver().ResolveAsDisposable<IRepository<OrganizationUnit, long>>())
        {
            var code = organizationUnitRepository.Object.Get(organizationUnitId).Code;

            var query =
                from entity in repository.GetAll()
                join organizationUnit in organizationUnitRepository.Object.GetAll() on entity.OrganizationUnitId equals organizationUnit.Id
                where organizationUnit.Code.StartsWith(code)
                select entity;

            return query.ToList();
        }
    }
}

用法:

var products = _productRepository.GetAllInOuIncludingChildren(organizationUnitId);
于 2018-04-12T13:10:59.900 回答
1

您可以使用以下代码。

界面:

public interface ITestRepository : IRepository<Test, int>
{

}

班级:

public class TestRepository : YourProjectNameRepositoryBase<Test, int>, ITestRepository
{
    public TestRepository(IDbContextProvider<YourProjectNameDbContext> dbContextProvider, IObjectMapper objectMapper)
        : base(dbContextProvider, objectMapper)
        {
        }
}

用法:

public class TestAppService : YouProjectNameAppServiceBase, ITestAppService
{
    private readonly ITestRepository _testRepository;
    public TestAppService(ITestRepository testRepository,
    
}

更新

在最新版本中,无需通过objectmapper,您需要使用以下更新的构造函数:

public class TestRepository : YourProjectNameRepositoryBase<Test, int>, ITestRepository
{
    public TestRepository(IDbContextProvider<YourProjectNameDbContext> dbContextProvider)
        : base(dbContextProvider)
        {
        }
}
于 2018-04-12T10:00:56.140 回答