如何在存储库模式中加载相关数据

时间:2016-11-23 15:15:57

标签: c# model-view-controller repository

我已经创建了一个非常基本的存储库模式,我希望包含一种加载相关数据的简洁方法。我以前见过人们使用.Include(),但我并不是100%肯定我会如何将它引入我的解决方案。

到目前为止,这是我的存储库:

/Repository/IRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.Repository
{
    public interface IRepository<T> where T : class
    {
        IEnumerable<T> GetAll();        
        T GetById(object Id);
        void Insert(T obj);
        void Update(T obj);
        void Delete(Object Id);
        void Save();
    }
}

/Repository/Repository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SeaBay.Models;
using System.Data.Entity;

namespace MyProject.Repository
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private myEntities db;
        private DbSet<T> dbSet;

    public Repository()
    {
        db = new myEntities();
        dbSet = db.Set<T>();
    }

    public IEnumerable<T> GetAll()
    {
        return dbSet;
    }

    public T GetById(object Id)
    {
        return dbSet.Find(Id);
    }
    //... etc etc
}

基本控制器

public class MyController : Controller
{
    private IRepository<entity> _repository = null;
    public MyController()
    {
        this._repository = new Repository<entity>();
    }

    public ActionResult Index()
    {
        var mydata = _repository.GetAll();
        return View(mydata);
    }

    public ActionResult Details(int Id)
    {
        var mydata = _repository.GetById(Id);
        return View(mydata);
    }
}

让我们说,我有两个数据表'学生'和'类',如果IRepository使用'学生'作为其来源,我将如何在存储库模式中返回这些相关数据?

1 个答案:

答案 0 :(得分:1)

人们没有跳过回答这个问题的最可能的原因是,通用存储库往往会导致非常漏洞的抽象或性能非常差的应用程序(你打算调用GetAll()并在只有25个时返回10,000个实体一次显示在页面上?)。从业务层和UI层中抽象出数据访问逻辑是很好的,但尝试创建一种通用的方法通常会导致过于简单化或过于复杂的事情。

尝试在通用存储库的顶部添加一个额外的抽象层,以便每个实体类型都有相应的存储库契约(接口)。然后创建一个实现合同的具体存储库类。具体类是您要确定要包含哪些数据以及何时包含的内容,并且合同可用于具有实体特定方法,重载等,以解释实体层次结构的复杂性。您的业​​务和UI层(直接或通过依赖注入)将与具体实现交互,而不是在业务和UI层中具有内部