Mitch
Mitch

Reputation: 2551

Add WHERE clause to every LINQ Select query

I'm using EF4 Code First in my Azure MVC app to retrieve data from an SQL Azure database.

The app will have approx 200 users in total divided over a dozen organisations all using the same app. The SQL Azure DB will be storing mainly Client contact info etc.

All the tables in the SQL Azure Database include a field called OrgansiationId which is a GUID that is unique to each organisation. All data saved includes the OrganisationId corresponding to the organisation of the person saving the data.

It's important that users only can add/edit/view information from their own Organisation.

So my question is, what is the recommended way of using LINQ to ensure that any Select statements only return information for the Users OrganisationId, without having to manually append "WHERE OrganisationId == organisationId" to every Select statement, which is vulnerable to human error. (ie Forgetting to include it so that the Organsation is not filtered, nightmare scenario!)

Is there an accepted way of acheiving this, possibly by wrapping a LINQ Statement with an additional WHERE statement so this is done automatically to all LINQ Select statements?

Upvotes: 1

Views: 1301

Answers (1)

Jan
Jan

Reputation: 16038

I have implemented a very similar app. I simply wrapped the DbContext in a wrapped context:

When this is the original context:

public class MyContext : DbContext {
    public DbSet<MyTable> MyTable { get; set; }
}

Then the wrapped context looks like this:

public class MyWrappedContext {
    protected MyContext InternalContext { get; set; }
    public Guid OrganizationId { get; set; }

    public IQueryable<MyTable> MyTable 
    {
        get 
        { 
            return InternalContext.MyTable
               .Where(t => t.OrganizationId == OrganizationId); 
        } 
    }
}

For adding, removing and updating entities i have the following methods on the WrappedContext:

public void Add<T>(T entity) where T : class
{
    DbEntityEntry<T> dbEntityEntry = InternalContext.Entry(entity);
    dbEntityEntry.State = EntityState.Added;
}

public void Remove<T>(T entity) where T : class
{
    DbEntityEntry<T> dbEntityEntry = InternalContext.Entry(entity);
    dbEntityEntry.State = EntityState.Deleted;
}

public void Update<T>(T entity) where T : class
{
    DbEntityEntry<T> dbEntityEntry = InternalContext.Entry(entity);
    dbEntityEntry.State = EntityState.Modified;
}

Upvotes: 2

Related Questions