在使用fakes框架时,我遇到了一些奇怪的行为。可能与ms fakes框架中的以下代码块有关:
public static implicit operator T(ShimBase<T> shim)
{
using (ShimRuntime.AcquireProtectingThreadContext())
{
return (shim == null) ? null : shim.GetInstance();
}
}
我尝试模拟ObjectSet
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 */
}
现在为什么?
花了很长时间才能识别出此错误。我进行了很多调查,但无法找到更多信息。