I have a DataContext
derived class that has many IDbSet
s 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 IDbSet
s, 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?
IDbSet<T>
is not a covariant interface, which means you can not assign IDbSet<Derived1>
variable to IDbSet<BaseClass>
variable. More on covariance here: https://msdn.microsoft.com/en-us/library/dd799517%28v=vs.110%29.aspx
IDbSet<T>
implements IQueryable<T>
which is a covariant interface and is the part of IDbSet<T>
that you want to use for querying.
You can try replacing the line:
var dbset = objects as IDbSet<BaseClass>;
with
var dbset = objects as IQueryable<BaseClass>;
You should be able to leave the rest of the code as is.