7

我正在使用 ASP.NET MVC4Entity Framework 5

基本上每个控制器操作结果都会通过登录的用户公司 ID 过滤数据库结果。我刚刚开始实现存储库模式来返回模型,而不是直接从控制器中过滤 DbContext。(将 companyID 传递到存储库以过滤方法的结果)

我有一种有趣的感觉,这样做是不好的做法,但一直无法找到有关该主题的任何信息。我将在下面插入我当前代码的基本版本,我将不胜感激任何关于它是否是不好的做法以及为什么会这样的信息。

IBookingSystemRepository.cs

public interface IBookingSystemRepository : IDisposable
{
    IEnumerable<Appointment> GetAppointments();
    IEnumerable<Appointment> GetAppointments(bool includeDeleted);
    IEnumerable<Client> GetClients();
    IEnumerable<Client> GetClients(bool includeDeleted);
    void Save();
}

BookingSystemRepository.cs

public class BookingSystemRepository : IBookingSystemRepository
{
    private BookingSystemEntities db;
    int CompanyID;

    public BookingSystemRepository(BookingSystemEntities context, int companyID)
    {
        this.db = context;
        this.CompanyID = companyID;
    }

    public IEnumerable<Appointment> GetAppointments()
    { return GetAppointments(false); }

    public IEnumerable<Appointment> GetAppointments(bool includeDeleted)
    {
        return includeDeleted
            ? db.Appointments.Where(a => a.User.CompanyID == CompanyID)
            : db.Appointments.Where(a => a.User.CompanyID == CompanyID && a.Deleted.HasValue);
    }

    public IEnumerable<Client> GetClients()
    { return GetClients(false); }

    public IEnumerable<Client> GetClients(bool includeDeleted)
    {
        return includeDeleted
            ? db.Clients.Where(c => c.CompanyID == CompanyID)
            : db.Clients.Where(c => c.CompanyID == CompanyID && c.Deleted.HasValue);
    }

    public void Save()
    {
        db.SaveChanges();
    }

    public void Dispose()
    {
        if (db != null)
            db.Dispose();
    }
}

测试控制器.cs

public class TestController : Controller
{
    private BookingSystemEntities db = new BookingSystemEntities();

    public ActionResult AppointmentsList()
    {
        var user = db.Users.Single(u => u.Email == User.Identity.Name);
        IBookingSystemRepository rep = new BookingSystemRepository(db, user.CompanyID);
        return View(rep.GetAppointments());
    }
}

预先感谢您的帮助:)

4

1 回答 1

4

它是一个多租户应用程序。需要过滤以保持每个公司的数据分开。你的方法是正确的;如果可能,请提供已过滤的上下文,而不是在下游存储库方法中单独过滤。

于 2013-06-17T15:27:39.153 回答