I’m working on ASP.Net MVC3 web-site with Entity Framework and SQL Server 2008 as a data storage. Also I’m using Repository pattern to concentrate all data-access code in one area.
In my application I have many users, every user can have many Projects. User should only have access to their own projects.
At the moment I have this code:
public IQueryable<Project> All
{
get {
return context.Projects
.Where(p => p.Owner.ID == Util.GetCurrentUserID())
.Select(p=>p);
}
}
public Project Find(System.Guid id)
{
return context.Projects
.Where(p => p.Owner.ID == Util.GetCurrentUserID())
.FirstOrDefault();
}
If you noticed .Where(p => p.Owner.ID == Util.GetCurrentUserID()) is duplicated. And I have quite a few other places where these exact conditions are littered.
Is there a way in DbContext to have this condition always appended automatically to any query going Projects table?
Something like:
public class MyContext : DbContext
{
public DbSet<Project> Projects
.Where(p => p.Owner.ID == Util.GetCurrentUserID()) { get; set; }
}
OR
public class MyContext : DbContext
{
public DbSet<Project> Projects { get {
// Insert a cast from IQuerieable to DBSet below
return Projects
.Where(p => p.Owner.ID == Util.GetCurrentUserID())
.Select(p => p);
}
set; }
}
UPD while writing the question, realised that the last version can just work – need to try out. Still would like to hear other options for code optimisation and making it more DRY.
Thanks in advance!!
You can always write an extension method called “WhereProject”. Then call the standard “Where” method in your extension method after appending your condition to your predicate.
You can skip predicate if you want or set it as null in the parameter list for default value and then act accordingly if you don’t want to use predicate.
This is probably what you want, it is simple:
EDIT
These solutions does not sound right to me. I think you would want to secure your row data one level higher, in my case it would be the service layer. Consider a method in your service class like this:
This way, from the method name, it is very clear what you are doing. It is not responsiblity of a repository to contain your specific logic. It is there to handle your data access only.