dimanche 17 mai 2015

EntityFramework SqlQuery and Reflection

I have been trying to generate a SiteMap for multiple websites for a custom CMS that I am writing.

My situation is as follows: I have a class in an Assembly called SiteMapItem:

public abstract class SiteMapItem
{
    public abstract string Url { get; }
}

I have three separate classes in a different Assembly that extend SiteMapItem:

public class Team : SiteMapItem
{ ... }

public class Partner : SiteMapItem
{ ... }

public class Project : SiteMapItem
{ ... }

In the Assembly that is going to generate the SiteMap, I am running the following code to get a list of the Types that have IsSubClassOf(typeof(SiteMapItem)):

foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
    if (a.GetTypes().Any(t => t.IsSubclassOf(typeof(SiteMapItem))))
    {
        winner = a;
    }
}

Once I have Winner, I get a list of Types that have the IsSubClassOf SiteMapItem:

List<Type> types = winner.GetTypes().Where(p => p.IsSubclassOf(typeof(SiteMapItem))).ToList();

I then Iterate over types to run the db.Database.SqlQuery - which is where I am stuck (db is a DataContext):

var items = db.Database.SqlQuery(t, "SELECT * FROM @table", new SqlParameter("table", t.Name"));

The above code returns nothing, When debugging, the type is set correctly for each iteration, However when I inspect items, and try to evaluate results, I get the error Children could not be evaluated.

I would normally use the alternative:

db.Database.SqlQuery<T>("SELECT * FROM @fdsfdsa", ...) 

but because I don't have a Class (Its in another assembly) I cannot.

Any help would be appreciated.





Aucun commentaire:

Enregistrer un commentaire