You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LINQ Select选择器类型转换失败:动态Retrieve函数调用报错

问题解决:动态Select选择器的类型转换错误

错误原因

你的函数使用dynamic作为Select选择器的返回类型,导致CRM的LINQ提供者无法确定实际返回类型,最终返回Query<object>,此时强制转换为IEnumerable<BookableResourceBooking>必然失败。而手动编写选择器时,返回类型明确为BookableResourceBooking,所以能正常运行。

修正方案

将函数改为泛型方法,让选择器的返回类型可明确指定,避免dynamic带来的类型模糊:

修正后的函数代码

public IEnumerable<T> RetrieveBookingsForWorkOrder<T>(Guid workOrderId, Expression<Func<BookableResourceBooking, T>> selector)
{
    return CrmServiceContext.BookableResourceBookingSet
        .Where(x => x.msdyn_WorkOrder.Id == workOrderId)
        .Select(selector);
}

调用方式(无需修改,泛型会自动推断类型)

.RetrieveBookingsForWorkOrder(
    workOrderId,
    x => new BookableResourceBooking() { Id = x.Id, StartTime = x.StartTime, EndTime = x.EndTime }
)

额外说明

如果你的场景中仅需要返回BookableResourceBooking类型,也可以直接固定选择器的返回类型,进一步简化:

public IEnumerable<BookableResourceBooking> RetrieveBookingsForWorkOrder(Guid workOrderId, Expression<Func<BookableResourceBooking, BookableResourceBooking>> selector)
{
    return CrmServiceContext.BookableResourceBookingSet
        .Where(x => x.msdyn_WorkOrder.Id == workOrderId)
        .Select(selector);
}

内容的提问来源于stack exchange,提问作者FelixTheMemelord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:40:28