开发者

Repository that accesses multiple tables

This model is simplified, only used for demonstration.

In my application got:

Data

public class Product
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
}

public class Category
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

Repository

public interface IRepository<T>
    where T : class
{
    T Add(T entity);
    T Remove(T entity);
    IQueryable<T> GetAll();
    int Save();
}

public class ProductRepository : IRepository<Product>
{
    public Product Add(Product entity) { ... }
    public Product Remove(Product entity) { ... }
    public IQueryable<Product> GetAll() { ... }
    public int Save() { ... }
}

public class CategoryRepository : IRepository<Category>
{
    public Category Add(Category entity) { ... }
    public Category Remove(Category entity) { ... }
    public IQueryable<Category> GetAll() { ... }
    public int Save() { ... }
}

Services

public interface ICategoryService
{
    Category Add(Guid gidProduct, Category category);
}

public class CategoryService : ICategoryService
{
    public Category Add(Guid gidProduct, Category category){ ... } //Pr开发者_如何学编程oblem here

    readonly IRepository<Category> _repository;

    public CategoryService(IRepository<Category> repository)  //Problem here
    {
        _repository = repository;
    }
}

As I have a repository for each class when I need information from another repository in my service, what should I do?

In the example above, in my service layer I have a method to Add a product (where I found the code for it) and a category.

The problem is that I do a search in the repository of products to recover it, but in my service class category, there is no repository of products., how to solve this problem?


First you need to create a repository for each aggregate root not for each class.

and if you need to access more than one repository in your service, simply you depend on all of them then you can add them as parameters to the constructor for dependency injection.

public CategoryService(CategoryRepository  categoryRepository, ProductRepository productRepository) 
{
    _categoryRepository = categoryRepository;
    _productRepository = productRepository;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜