Question

There are many tables in the database that are used as "lookup" tables. All the tables have the same structure, other than the ID column name.

I have found that I can use reflection to open a table and enumerate through the records. The method takes a string (tableName).

Uri serviceUri = new Uri("http://localhost/MyDataService/WcfDataService.svc");
var context = new MyEntities(serviceUri);
var eTable = typeof(MyEntities).GetProperty(tableName).GetValue(context, null) as IEnumerable<object>
foreach (object o in eTable)
...

This works fine, but I want to add a WHERE clause to the query. For example, where InactiveDate == null.

Can I do this? I have been unable to figure this one out.

Was it helpful?

Solution

How about this?

var eTable = (typeof(MyEntities).GetProperty(tableName).GetValue(context, null) as IEnumerable<object>).Where(obj => obj.GetType().GetProperty("InactiveDate").GetValue(obj) == null);
foreach (object o in eTable) 

OTHER TIPS

I would suggest to use generics and maybe an interface over reflection.

public function Xyz<TEntity>(Func<MyEntities, IDbSet<TEntity>> dbSetGetter, Expression<Func<TEntity, Boolean>> filter)
{
   var serviceUri = new Uri("http://localhost/MyDataService/WcfDataService.svc");

   using (var context = new MyEntities(serviceUri))
   {
      foreach (var entity in dbSetGetter(context).Where(filter))
      {
         DoSomethingWith(entity);
      }
   }
}

Usage would be like this

Xyz(context => context.Foo, foo => foo.Bar == 42);

assuming you have an entity Foo with an integer property Bar. The obvious difference to your code is that you have to know the entity type a compile time and I am not sure if you know it then.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top