C# 如何在泛型中迭代所有数据库集?
(我在这里使用的是EF6) 假设我有一个抽象类:C# 如何在泛型中迭代所有数据库集?,c#,entity-framework,reflection,iteration,C#,Entity Framework,Reflection,Iteration,(我在这里使用的是EF6) 假设我有一个抽象类: public abstract class MyContext<T> : DbContext var dbSetProperties = typeof(T).GetProperties().Where(p => p.PropertyType == typeof(DbSet<>)); 公共抽象类MyContext:DbContext 让我们使用它: public class MyTestContext : MyC
public abstract class MyContext<T> : DbContext
var dbSetProperties = typeof(T).GetProperties().Where(p => p.PropertyType == typeof(DbSet<>));
公共抽象类MyContext:DbContext
让我们使用它:
public class MyTestContext : MyContext<MyTestContext>
{
public DbSet<Object1> Object1 { get; set; }
public DbSet<Object2> Object2 { get; set; }
}
公共类MyTestContext:MyContext
{
公共DbSet Object1{get;set;}
公共数据库集对象2{get;set;}
}
现在,假设我想在我的抽象类中迭代MyTestContext中的所有数据库集。这似乎可行(这是我抽象类中的一个方法):
var dbSetProperties=typeof(T).GetProperties()。其中(p=>p.PropertyType==typeof(DbSet));
但我得到的是“枚举没有结果”
我做错了什么?谢谢
编辑说明-我不希望预先知道泛型类型参数-我实际上是想确定每个数据库集中的类型。因此Foo
不是Foo
类型。您需要获取Foo
s的泛型类型定义并进行比较
var dbSetProperties = typeof(MyTestContext)
.GetProperties()
.Where(p => p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>));
var dbSetProperties=typeof(MyTestContext)
.GetProperties()
其中(p=>p.PropertyType.GetGenericTypeDefinition()==typeof(DbSet));
属性不是DbSet类型,它们的一般定义是.Ha,回想起来似乎很明显。谢谢,成功了。我会在……中给你答案。。。啊。。6分钟:)