InvalidCastException可能是由在false框架中重写隐式强制转换引起的

时间:2018-11-16 08:39:28

标签: c# entity-framework-6 microsoft-fakes

在使用fakes框架时,我遇到了一些奇怪的行为。可能与ms fakes框架中的以下代码块有关:

    public static implicit operator T(ShimBase<T> shim)
    {
        using (ShimRuntime.AcquireProtectingThreadContext())
        {
            return (shim == null) ? null : shim.GetInstance();
        }
    }

我尝试模拟ObjectSet 的响应。通过执行以下操作来查询ObjectQuery

internal class MyObjectEnumerable<TEntity> : ShimObjectQuery<TEntity>, IDbAsyncEnumerable<TEntity>, IQueryable<TEntity>
{
    internal MyObjectEnumerable(ObjectQuery query) : base()
    {            
        var _ = new ShimObjectQuery(query);
        IncludeString = path => Instance;

        Bind(this.AsEnumerable());
        Bind(this.AsQueryable());
        Bind((IDbAsyncEnumerable<TEntity>)this);
    }

    /* further shim implementation */
}

internal class MyObjectQueryProvider<TEntity> : IDbAsyncQueryProvider
{
    public IQueryable CreateQuery(Expression expression)
    {
        // consuming the upper class
        var shim = new MyObjectEnumerable<TEntity>(_query);

        // this causes the InvalidCastExeption: MyObjectEnumerable<TEntity> to ObjectQuery in 
        // System.Data.Entity.QueryableExtensions.CommonAsNoTracking<T>(T source)
        return shim; 

        // this avoids the implicit cast and works
        return shim.Instance; 
    }

    /* further shim implementation */
}

现在为什么?

花了很长时间才能识别出此错误。我进行了很多调查,但无法找到更多信息。

0 个答案:

没有答案