尝试返回BaseClass类型的DbSet

时间:2014-11-05 10:43:59

标签: c# mocking entity-framework-6

我试图在它是Baseclass时返回TEntity类型的DbSet。

我所拥有的是两个带有基类的类。它们都在数据库的同一个表中。

private FakeDbSet<BaseClass> allclasses { get; set; }

enter image description here

所以在我的代码中我使用以下代码设置正确的数据库:

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) 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);

                    // you will need to convert FakeDbSet<TBaseType> to FakeDbSet<TEntity>
                    //This is a try but it will not work!!!
                    var entityDbSet = Convert.ChangeType(baseTypeDbSet, typeof(FakeDbSet<>).MakeGenericType(baseType));
                    var result = entityDbSet as FakeDbSet<TEntity>;
                    return result;
                }
            }
            baseType = baseType.BaseType;
        }

现在我的问题是:,因为您看到我正在尝试返回FakeDbSet<TEntity>。当我Set<Class1>()时,它进入第二个循环。问题是该函数期望返回类型为FakeDbSet<TEntity>(在本例中为FakeDbSet<Class1>)但我希望在这种情况下返回BaseClass:FakeDbSet<BaseClass>

0 个答案:

没有答案
相关问题