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!!