目前我正在用 MVC 4 编写一个 Web 应用程序。我使用的是通用存储库模式。它运作良好。所以我有以下类似的东西,
public class AddressRepository : IAddressRepository
{
private AISDbContext context = new AISDbContext();
public IQueryable<Address> GetAddresses()
{
return context.Address;
}
}
但是现在我需要添加一些东西来更多地过滤数据。根据登录用户的角色,应该对这些数据进行更多过滤。
像这样的东西..
public IQueryable<Address> GetAddresses()
{
return context.Address.where(x=>x.haspermissions = CURENTUSER.Role);
}
现在我总是可以添加另一个这样的功能,但我想尝试一个通用的。我想知道我是否可以只使用第一段代码并从另一个类继承,这只是应用安全修整。这样我就不必重写所有查询,我只需告诉每个类从安全修剪器继承。希望这是有道理的..
谢谢
更新代码
public class AddressRepository : SecureRepositoryBase<Address>, IAddressRepository
{
private AISDbContext context = new AISDbContext();
public IQueryable<Address> GetAll()
{
return base.RetrieveSecure(context.Address, 1);
}
}
public abstract class SecureRepositoryBase<T> where T : ISecuredEntity
{
public IQueryable<T> RetrieveSecure(IQueryable<T> entities, int currentUser)
{
return entities.Where(e => e.InspectorId == currentUser);
}
}
public interface ISecuredEntity
{
int? InspectorId { get; set; }
}
public class Address: ISecuredEntity
{
public int COESNo { get; set; }
public int Postcode { get; set; }
public int AuditAuthNo { get; set; }
public bool? SelectedForAudit { get; set; }
public int? RECId { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public int? CustomerSuburbId { get; set; }
public int? InspectorId { get; set; }
public DateTime? AuditDate { get; set; }
public int? AuditType { get; set; }
public int? UploadType { get; set; }
public string COESImage { get; set; }
public DateTime CreatedDate { get; set; }
public int? CreatedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public int? ModifiedBy { get; set; }
public virtual UserDetails Inspector { get; set; }
public virtual Postcodes CustomerSuburb { get; set; }
public virtual ResponsiblePerson RPerson { get; set; }
public virtual UserProfile CreatedByUser { get; set; }
public virtual UserProfile ModifiedByUser { get; set; }
}