0

Does anyone have any idea how to limit result set of EntityFramework permanently? I'm speaking about something like this Conditional Mapping. This is exactly what I want to achieve with one exception: I want to do this programmatically. That's because condition value will be passed to EF only on context creation. Beside I don't want this column to disappear from mapping.

I know how to achieve this with EF2.0 and reflection. I was using CreateQuery() method to generate my own ObjectQuery. CreateQuery() allows to inject my own ESQL query with additional condition e.g. WHERE TABLE.ClientID == value.

Problem with EF40 is that there is no more ObjectQuery but only ObjectSet and CreateQuery() is not used. I have no idea how to inject my own ESQL query.

The reason why I want to limit result sets is that I want to separate clients data from each other. This separation should be done automatically inside context so that programmers will not have to add condition .Where(x => x.ClientID == 5) to each individual query.

Maybe my approach is completely bad — but I don't know any alternative.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
yntelo
  • 3
  • 1

1 Answers1

1

You don't need reflection for this. You can simply use class inherited from ObjectContext or create custom implementation of UnitOfWork and Repositories which will wrap this functionality in better way (upper layer has access only to UnitOfWork and Repositories which do not expose EF context).

Simple example of object context:

public class CustomContext : ObjectContext
{
  private ObjectSet<MyObject> _myObjectsSet;
  private int _clientId;

  public CustomContext(string connectionString, int clientId)
    : base(connectionString)
  {
    _myObjectSet = CreateObjectSet<MyObject>();
    _clientId = clientId;
  }

  public IQueryable<MyObject> MyObjectQuery
  {
    get
    {
      return _myObjectsSet.Where(o => o.ClientId == _clientId);
    }
  }
}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Thx, this looks fine. Quite a lot coding :) I thought it could be done automatically e.g. by iterating throu entity sets and injecting some – yntelo Nov 23 '10 at 17:02
  • ... some query. But this approach is appropriate for me. I'm glad there is an alternative way. – yntelo Nov 23 '10 at 17:04
  • I run into another problem. Using your example I'm unable to use .Include(...). Include is very useful and convenient. So how to return ObjectQuery with additional condition? – yntelo Nov 29 '10 at 15:39
  • Any idea how to do what the original poster asked? – Josh Mouch May 03 '12 at 01:09
  • @Josh: The original question doesn't have solution because EF doesn't support any kind of global filters. – Ladislav Mrnka May 03 '12 at 09:12