使用$ expand的OData由于包装而中断了转换操作

par*_*ent 10 c# odata asp.net-web-api

我遇到了与此处相同的问题:

但是,答案对我来说还不够.首先,我不能为我的生活找到HierarchyNodeExpressionVisitorOData 5.0.0(不是RC1)(或任何地方,尝试谷歌搜索).

第二,即使我确实发现它返回IHttpActionResult不够好,我需要返回一个打字PageResult<MyViewModel>

所述归还的理由IHttpActionResult是"处理结果可能不再存在的事实IQueryable<MyEntity>".一旦使用$ expand运算符.

但这对我来说没有意义,因为我认为$ expand运算符用于在实体上包含导航属性,就像服务器端Include(e => e.RelatedProperty)一样.至少在我的情况下,我只包括已经在实体上的属性,所以我不必担心它"可能是其他东西".

但是当使用$expand=Department我不能Cast<>()实体类型因为它无法强制SelectAllAndExpand<MyEntity>转换为MyEntity.

如何将展开"展开"回原始实体,以便我可以进行投影?

public PageResult<DateSnippetWithDepartmentsViewModel> GetDatesWithDepartments(ODataQueryOptions<DateSnippet> options)
{
    IQueryable query = options.ApplyTo(_context.DateSnippets, new ODataQuerySettings());;

    //Exception when using $expand.. cannot cast SelectAllAndExpand<DateSnippet> to DateSnippet
    List<DateSnippet> dateSnippets = query.Cast<DateSnippet>().ToList();

    var dateSnippetsViewModels = (from d in dateSnippets
                                    select new DateSnippetWithDepartmentsViewModel
                                    {
                                        ...
                                    });

    var result = new PageResult<DateSnippetWithDepartmentsViewModel>(
            dateSnippetsViewModels as IEnumerable<DateSnippetWithDepartmentsViewModel>,
            Request.GetNextPageLink(),
            Request.GetInlineCount());

    return result;
}
Run Code Online (Sandbox Code Playgroud)

Aro*_*ron 1

尝试这个。希望应该可以工作,当我们到达枚举器时,结果应该是一个DateSnippet. 您之前所做的就是尝试在 Linq 表达式树中进行转换。我怀疑在 IQueryable 执行中,它是被解析和转换的,而不是强制转换。

public PageResult<DateSnippetWithDepartmentsViewModel> GetDatesWithDepartments(ODataQueryOptions<DateSnippet> options)
{
    IQueryable query = options.ApplyTo(_context.DateSnippets, new ODataQuerySettings());;

    List<DateSnippet> dateSnippets = new List<DateSnippet>();
    foreach(DateSnippet item in query)
    {
        dateSnippets.Add(item);
    }

    var dateSnippetsViewModels = (from d in dateSnippets
                                    select new DateSnippetWithDepartmentsViewModel
                                    {
                                        ...
                                    });

    var result = new PageResult<DateSnippetWithDepartmentsViewModel>(
            dateSnippetsViewModels as IEnumerable<DateSnippetWithDepartmentsViewModel>,
            Request.GetNextPageLink(),
            Request.GetInlineCount());

    return result;
}
Run Code Online (Sandbox Code Playgroud)