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

I am using ASP.NET MVC4 with Entity Framework 5 .

Essentially every controller action result filters the db results by the logged in Users' Company ID . I have just begun implementing a repository pattern to return the models rather than directly filtering the DbContext from the controller. (Passing the companyID into the repository to filter results of methods)

I have a funny feeling that it is bad practice to do this, but have been unable to find any information on the subject. I will insert a basic version of my current code below, I would appreciate any information about whether or not it is bad practice, and why so.

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

Thankyou in advance for your assistance :)


It is a multi-tenant application. The filtering is needed to keep each company's data separate. Your approach is a sound one; if possible, provide a context that is already filtered, rather than filtering in the downstream repository methods individually.

链接地址: http://www.djcxy.com/p/72000.html

上一篇: 在php中处理json序列化表单数据

下一篇: 在存储库模式中通过ID进行筛选是不好的做法