title: Using Reflection and LINQ to query the ApplicationDataService
body: <p>I am using the VS Lightswitch ServerApplicationContext to access and modify lightswitch data entities within an ApiController.</p>
  
  <p>Let's say I have a Customer entity, and i can query the collection of customers in the lightswitch db using linq:</p>
  
  <pre><code>IEnumerable&lt;Customer&gt; customers = from custs in serverContext.DataWorkspace
                                                               .ApplicationData
                                                               .Customers
                                                               .GetQuery()
                                                               .Execute()
                                    where c.AProperty == aProperty
                                    select custs;
  </code></pre>
  
  <p>or</p>
  
  <pre><code>IEnumerable&lt;Customer&gt; customers = 
                          serverContext.DataWorkspace
                                       .ApplicationData
                                       .Customers
                                       .Where(c =&gt; c.AProperty == aProperty)
                                       .Execute();
  </code></pre>
  
  <p>This works perfectly. </p>
  
  <p>However, I have many more entities and several projects with different entities in each project and I am trying to create a library to allow me to query <code>ServerApplicationContext</code> using reflection.</p>
  
  <p>I have used reflection to get the properties of the <code>ServerApplicationContext</code> object, which gives me access to the <code>EntitySet&lt;T&gt;</code>, but I can not execute any queries against it.</p>
  
  <p>This is the code as it stands:</p>
  
  <pre><code>Type t = serverContext.DataWorkspace.ApplicationData.GetType();
  PropertyInfo[] pInfo = t.GetProperties();
  foreach (var p in pInfo)
  {
      // p is equal to {Microsoft.LightSwitch.Framework.EntitySet`1[LightSwitchApplication.Customer] Customers}
      MethodInfo mInfo = p.PropertyType.GetMethod("GetQuery");
      var result = mInfo.Invoke(p.PropertyType, null) ; //&lt;-- Error Here
  }
  </code></pre>
  
  <p>The error returned  is:</p>
  
  <blockquote>
    <p>An exception of type 'System.Reflection.TargetException' occurred in mscorlib.dll but was not handled in user code
    Additional information: Object does not match target type.</p>
  </blockquote>
  
  <p>Has anyone had any joy with querying <code>EntitySets</code> (including where clauses) using reflection?</p>