使用存储库模式创建多对多关系

Creating Many-to-many relationship with repository pattern

我有一道菜和类别 tables,看起来像这样:

public class Dish {

    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public decimal Price { get; set; }

    public string Description { get; set; }

    public ICollection<UserDish> UserDishes { get; set; }

    public ICollection<DishCategory> DishCategories { get; set; }

}
public class Category {

    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public ICollection<DishCategory> DishCategories { get; set; }

}

而且我有每个接口和实现的接口

public class EFDishRepository : IDishRepository {

    private ApplicationDbContext _context;

    public EFDishRepository(ApplicationDbContext ctx) {
        _context = ctx;
    }

    public IQueryable<Dish> Dishes => _context.Dishes;

}
public class EFCategoryRepository : ICategoryRepository {
    private readonly ApplicationDbContext _context;

    public EFCategoryRepository(ApplicationDbContext ctx) {
        _context = ctx;
    }

    public IQueryable<Category> Categories => _context.Categories;
}

我有一个由 fluent API 映射的多对多关系。

我的问题是处理 DishCategory table 的最佳实践是什么?

我是否应该创建单独的存储库来处理它,因为从 DishCategory 方面处理它感觉不对?

what is the best practice going about dealing with DishCategory table?

它们应该在同一个存储库中。您的 ApplicationDbContext 是一个非常好的存储库。首先没有理由将它包装在单独的存储库 类 中。

如果你走这条路,你将不断地在你的存储库中添加和更改方法以在你的应用程序中实现业务逻辑,并且你的存储库最终将充满属于存储库外部的代码,例如查询和事务.

如果您想要一个单一实体存储库,您应该至少 有一个方法来访问 DbContext 以访问其他实体。下面是一个简单的单一实体接口的想法,使用 C# 8 的新默认接口实现功能。

public interface IRepository<T> where T:class
{
    public DbSet<T> Set
    {
        get 
        {
            var db = (DbContext)this;
            return db.Set<T>();

        }
    }
    public T Find(int id)
    {
        return Set.Find(id);
    }        

    //. . .
}