簡體   English   中英

在存儲庫模式中按ID過濾是不好的做法

[英]Is it bad practice to filter by ID within the repository pattern

我正在使用ASP.NET MVC4Entity Framework 5

基本上每個控制器操作結果都按登錄的用戶公司ID過濾db結果 我剛剛開始實現一個存儲庫模式來返回模型,而不是直接從控制器中過濾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();
    }
}

TestController.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());
    }
}

謝謝你提前幫助:)

這是一個多租戶應用程序。 需要過濾以保持每個公司的數據分開。 你的方法很合理; 如果可能,請提供已過濾的上下文,而不是單獨過濾下游存儲庫方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM