samedi 11 avril 2015

Iterating all Entity Framework DbSets that implement an Interfcae using reflection

Some of my Entity Framework classes implement a certain interface, say IHasYearColumn, which means the table has a year column (int).


I would like to iterate over all of the tables with year columns and do some work.


I managed to get the relevant types using:



var typesWithYear = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a=>a.GetTypes())
.Where(t=>typeof(IHasYearColumn).IsAssignableFrom(t);


I verified this works, and indded I get all the types I want.


Now, I would like to iterate over the respective table get the year values from all the records:



foreach (t in typesWithYear)
myDbEntites.Set<t>().Select(x=>x.Year);


This obviously won't compile since t is not recognized as IHasYearColumn. So, I tried casting all types in typesWithYear into IHasYearColumn but this would not help. I got an InvalidCastException.


Any ideas will be most welcomed.






Aucun commentaire:

Enregistrer un commentaire