以下是简化的Entity Framework 6上下文,我正在尝试使用反射来将实体填充到List中,但在如何进行转换方面遇到了问题。
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>();
//...
}
}
}
我正在为一些集成测试编写实用方法。我试图在不使用直接的内联SQL调用(如使用SqlConnection和SqlCommand等)访问数据库的情况下完成此操作(因为数据存储可能更改为Oracle等)。
IEnumerable
接口。 - Alexey NisDbSet<>
不是列表,而且DbSet<Foo>
和List<Foo>
都不是List<object>
。你试图做的事情注定会失败。你能澄清一下你的意图吗?你想要做什么? - Marc Gravellnew List<T>(dbSet)
。 - Jaanus Varuspi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet<>)
。 - LeeIsGenericType
。 - Marc Gravell