Is it Possible to use reflection on LINQ to Entities to query a dynamic table?

StackOverflow https://stackoverflow.com/questions/23408903

  •  13-07-2023
  •  | 
  •  

Вопрос

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.

Это было полезно?

Решение

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) 

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top