jeudi 7 mai 2015

Reflecting over IDbSets using base class

I have a DataContext derived class that has many IDbSets that are subclasses of a base class:

public class BaseClass
{
    public int Id {get; set;}
    public int Length {get; set;}
    public int Height {get; set;}
}

public class Derived1 : BaseClass
{
    public string SomeProperty {get; set}
}

public class Derived2 : BaseClass
{
    public string SomeProperty {get; set}
}

public class Derived3 : BaseClass
{
    public string SomeProperty {get; set}
}

public class Derived4 : BaseClass
{
    public string SomeProperty {get; set}
}

public class MyContext : DbContext {
    public IDbSet<Derived1> set1 {get; set;}
    public IDbSet<Derived2> set2 {get; set;}
    public IDbSet<Derived3> set3 {get; set;}
    public IDbSet<Derived4> set4 {get; set;}
}

I actually have many more derived classes and corresponding IDbSets, and I want to use reflection on the MyContext class and iterate over them to retrieve and inspect properties that exist on the base class, but when I try to cast the IDbSet as IDbSet<BaseClass> it comes back null.

        using (var db = new ValidationDataContext())
        {
            try
            {
                Type t = db.GetType();
                if (t != null)
                {
                    foreach (PropertyInfo prop in t.GetProperties())
                    {
                        var objects = (t.InvokeMember(prop.Name, BindingFlags.GetProperty, null, db, null));

                        var dbset = objects as IDbSet<BaseClass>;
                        if (dbset != null) //dbset is always null
                        {
                            dbset.Where(v => v.Length <= 0)
                                .ForEach(v => Debug.WriteLine("Bad Length"));
                        }
                    }
                }
            }
        }

Is there a way to do this?





Aucun commentaire:

Enregistrer un commentaire