无法将 IQueryable<T> 隐式转换为自定义类型,但其他类型可以

Cannot implicitly convert IQueryable<T> to a custom type, but other types work

我的应用程序的业务逻辑层执行自己的授权检查和所有数据查询操作return一个GuardedResult<TResult>值,定义如下:

public class GuardedResult<TResult> {
    public TResult Result { get; }
    public Status Status { get; }
    public GuardedResult(TResult result, Status status) {
        this.Result = result;
        this.Status = status;
    }
    public static implicit operator GuardedResult<TResult>(TResult result) {
        return new GuardedResult<TResult>(result, Status.Success);
    }
}

这样使用:

public partial class EmployeesBusinessLogic {

    public GuardedResult<Employee> GetEmployee(Int64 employeeId) {

        if( this.CurrentUser.CanReadAll ) {

            return this.Data.Employees.GetEmployeeById( employeeId );

        }
        else if( this.CurrentUser.CanReadSelf ) {

            if( this.CurrentUser.EmployeeId == employeeId ) {

                return this.Data.Employees.GetEmployeeById( employeeId );
            }
            else {

                return new GuardedResult<Employee>( null, Status.AccessDenied );
            }
        }
        else {
            return new GuardedResult<Employee>( null, Status.AccessDenied );
        }
    }
}

这构建并运行良好。

然而,当我将 TResult 更改为封闭通用 IQueryable 时,它失败了:

public GuardedResult<IQueryable<Employee>> GetEmployees() {

    if( this.CurrentUser.CanReadAll ) {

        return this.Data.Employees.GetAllEmployees();
    }
    else {

        return new GuardedResult<IQueryable<Employee>>( null, Status.AccessDenied );
    }
}

编译错误为:

Error CS0266
Cannot implicitly convert type 'System.Linq.IQueryable<Initech.Employee>' to 'Initech.GuardedResult<System.Linq.IQueryable<Initech.Employee>>'.
An explicit conversion exists (are you missing a cast?)

这里是EmployeesDataclass的相关定义:

public IQueryable<Employee> GetAllEmployees() {
    return this.dbContext.Employees;
}

public Employee GetEmployeeById(Int64 employeeId) {
    return this.dbContext.Employees.SingleOrDefault( e => e.EmployeeId == employeeId );
}

我知道我在这里没有回答你想要的,但 as it turns out, the implicit casting operator won't work in your case (and although confusingly, the why is in the specs, but don't let me try to make sense of it, and see the answer 为什么)

然后,对于您的具体情况,这将是一个问题:

return new GuardedResult<IQueryable<Employee>>(
          this.Data.Employees.GetAllEmployees(), Status.Success);

同样,很可能不是您想听到的