I want to convert following to list. I have fetched property using reflection, but how to convert them to list (in my case this is entity object DBSet).
and I need the result as list.
ClassObject.GetType().GetProperty(classname) //After getting property I need it in .ToList()
You can convert with a function like this.
If the reflected object is not enumerable, it can't be converted.
public static List<T> ConvertMysteriousObjectToList<T>(object input)
{
var enumerable = input as IEnumerable;
if (enumerable == null) throw new InvalidOperationException("The object is not convertible to a list.");
return enumerable.Cast<T>().ToList();
}
If you're trying to convert some flavor of DbSet (eg a DbSet<Foo>
) then you'd call it like this:
var o = ClassObject.GetType().GetProperty(classname);
var list = ConvertMysteriousObjectToList<Foo>(o);
If you don't know the type:
var list = ConvertMysteriousObjectToList<object>(o);
or
var list = ConvertMysteriousObjectToList<dynamic>(o);
I got what I wanted.
static IEnumerable GetAllMembers(DbContext db, string dbSetName)
{
var pi = db.GetType().GetProperty(dbSetName);
return (IEnumerable)pi.GetValue(db);
}
source: How to get DbSet<SomeClass> (EF) from the dbContext using reflection?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.