我正在尝试将DbSet<BaseContact>
投射到DbSet<TEntity>
。我的问题如下所示,我正在尝试输入Contact
并将其转换为DbSet<BaseContact>
,但我只能返回DbSet
类型DbSet<TEntity>
。 BaseContact
是Contact
的超类。
我怎么能做这个演员?有什么建议吗?
//Input: Set<Contact> -> Output: DbSet<BaseContact>
public DbSet<TEntity> Set<TEntity>()
where TEntity : class, IObjectState
{
Return DBSet<BaseContact> as DBSet<TEntity>;
}
PS:使它不通用是没有选择的,因为我正在通过它运行其他类型。上面的代码不是整个函数。
这是完整的功能:
public DbSet<TEntity> Set<TEntity>()
where TEntity : class, IObjectState
{
var propertyInfos = GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (PropertyInfo property in propertyInfos)
{
if (property.PropertyType == typeof(FakeDbSet<TEntity>))
return property.GetValue(this, null) as FakeDbSet<TEntity>;
}
var baseType = typeof(TEntity).BaseType;
while( typeof(object) != baseType )
{
foreach(var property in propertyInfos)
{
if(property.PropertyType == typeof(FakeDbSet<>).MakeGenericType(baseType))
{
var baseTypeDbSet = property.GetValue(this, null);
// you will need to convert FakeDbSet<TBaseType> to FakeDbSet<TEntity>
var entityDbSet = Convert.ChangeType(baseTypeDbSet, typeof(FakeDbSet<>).MakeGenericType(baseType)) as FakeDbSet<TEntity>;
return entityDbSet;
}
}
baseType = baseType.BaseType;
}
throw new Exception("Type collection not found");
}