如果您不熟悉 Entity Framework ,它会生成一个如下所示的类
public partial class contextontext : DbContext
{
public virtual DbSet<foo> foo { get; set; }
public virtual DbSet<bar> bar { get; set; }
//Etc, there could be lots of these DbSet properties
}
我正在尝试构建一个类型列表 DbSet<T>
集合,但我不确定如何检查泛型类型。我使用PropertyType.ToString().StartsWith("System.Data.Entity.DbSet`1")
让它工作但这似乎是一种困惑且不必要的复杂方法。这是我用来获取属性的完整 LINQ。
foreach (var property in context.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(p => p.PropertyType.ToString().StartsWith("System.Data.Entity.DbSet`1")))
{
Type type = property.PropertyType.GenericTypeArguments[0];
//other stuff...
}
我在属性对象中查找了一下,但没有找到任何线索。有一个Type
在那里,但这始终是通用 DbSet 的特定于类型的实现(因为它应该是这样)。我如何检查它是否是通用集合,无论它是什么类型?
最佳答案
我认为你想要的只是:
var propertyType = property.PropertyType;
if (propertyType.IsGenericType
&& propertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
{
// ...
}
我现在看到你的 Where
在你的代码的右边。那将是:
.Where(p => p.PropertyType.IsGenericType
&& p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
method GetGenericTypeDefinition
从具体构造(“封闭”)泛型类型(例如 DbSet<foo>
)到类型的定义(此处为 DbSet<TEntity>
)。
关于c# - 查找属于同一泛型类的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31416696/