Given the following simplified Entity Framework 6 context, I am trying to populate a List with the entities but having problems with how to cast (I believe) via reflection.
public class FooContext : DbContext
{
public virtual IDbSet<FooClass> Foo { get; set; }
//...
}
public class FooClass
{
public int Id{ get; set; }
public string Name {get; set; }
//...
}
public main()
{
using (var context = new FooContext())
{
var sets = typeof(FooContext).GetProperties().Where(pi => pi.PropertyType.IsInterface && pi.PropertyType.GetGenericTypeDefinition().ToString().ToLower().Contains("idbset"));
foreach (var set in sets)
{
//When I debug and enumerate over 'value' the entire results are shown so I believe the reflection part is OK.
var value = set.GetValue(context, null);
//Always returns null. How can I cast DbSet<T> to List<object> or List<T>?
var list = value as List<object>();
//...
}
}
}
I'm doing this for utility method for some integration testing I am doing. I am trying to do this without using direct inline SQL calls (using SqlConnection and SqlCommand etc) to access the database (as the datastore may change to Oracle etc).
IDBSet inherits from IQueryable<TEntity>
, IEnumerable<TEntity>
, IQueryable
, and IEnumerable
, so you can't directly cast it to a list that way.
You could get a List<TEntity>
of all entities in the DBSet
though by using .ToList()
or .ToListAsync()
THis creates a copy of all entities in memory though, so you should consider operating with LINQ directly on the DBSet