如何铸造DbSet< T>到列表< T> [英] How to cast DbSet<T> to List<T>
问题描述
给定以下简化的Entity Framework 6上下文,我试图填充一个列表与实体,但有如何通过反射铸造(我相信)的问题。
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>();
//...
}
}
}
我这样做的实用程序方法进行一些集成测试我在做。我试图这样做而不使用直接内联SQL调用(使用SqlConnection和SqlCommand等)来访问数据库(因为数据存储可能会更改为Oracle等)。
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继承自 IQueryable< TEntity>
, IEnumerable< TEntity>
, IQueryable
和 IEnumerable
,因此您不能直接将其强制转换为列表。
你可以得到 DBSet
中所有实体的 List
$ c> .ToList()或 .ToListAsync()
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()
所有实体在内存中的副本,所以你应该考虑直接在DBSet上使用LINQ
THis creates a copy of all entities in memory though, so you should consider operating with LINQ directly on the DBSet
这篇关于如何铸造DbSet< T>到列表< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!