Kyl*_*yle 10 c# reflection casting entity-framework-6
鉴于以下简化的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>();
//...
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在为实用程序方法执行此操作,以进行一些集成测试.我试图这样做,而不使用直接内联SQL调用(使用SqlConnection和SqlCommand等)来访问数据库(因为数据存储可能会更改为Oracle等).
LIn*_*Teh 11
IDBSet继承IQueryable<TEntity>,IEnumerable<TEntity>,IQueryable,和IEnumerable,所以你不能直接将其转换为一个列表的方式.你可以通过使用或获得List<TEntity>所有实体DBSet.ToList().ToListAsync()
这会创建内存中所有实体的副本,因此您应该考虑直接在DBSet上使用LINQ
小智 10
//dont forget using System.Linq;
using (var context = new FooContext())
{
IQueryable<FooClass> rtn = from temp in context.Foo select temp;
var list = rtn.ToList();
}
Run Code Online (Sandbox Code Playgroud)
除了 VicYam 的回答外,这里还有一种更简单的方法,并附有详细说明。
添加System.Linq命名空间后,您不再需要获取IQueryable然后转换为List. 相反,您将获得DbSet对象的扩展方法。
这是什么意思?您可以简单地单独返回 ,DbSet因为它继承自IEnumerable。消费者,可能是开发人员,然后可以执行.ToList他们可能需要的列表类型或任何其他列表类型。
最简单
这将返回DbSet原样,它已经继承IEnumerable了一个列表类型,然后可以将其转换为List.
List<ObjectType> list = new List<ObjectType>();
using (var context = new FooContext())
{
list = context.Foo;
}
Run Code Online (Sandbox Code Playgroud)
选择
您可以立即将 from 转换IEnumerable为List.
using (var context = new FooContext())
{
var list = context.Foo.ToList();
}
Run Code Online (Sandbox Code Playgroud)
仍然想要 VicYam 的答案,但作为一行?
using (var context = new FooContext())
{
var list = context.Foo.AsQueryable().ToList();
}
Run Code Online (Sandbox Code Playgroud)