Linq查询错误 [英] Linq query error

查看:59
本文介绍了Linq查询错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下Linq查询:

I am using following Linq query:

from p in People
 where p.Name == "George Lucas"
select p.TitlesActedIn

其中TitlesActedIn是一个列表.人物和头衔ActedIn相关联

where TitlesActedIn is a list. People and TitlesActedIn are associted

但是我遇到了错误:

InvalidCastException:无法将类型为"System.Linq.Expressions.PropertyExpression"的对象转换为类型为"System.Data.Services.Client.ResourceExpression".

InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.PropertyExpression' to type 'System.Data.Services.Client.ResourceExpression'.

请提出解决方案.

推荐答案

一种非常简单的方法:

var query = People
    .Expand("TitlesActedIn")
    .Where(p => p.Name == "George Lucas")
    .First()
    .TitlesActedIn.Select(t => t.ShortName);              
query.Dump();

需要注意的重要一点是,如果您传递的名称不存在,则会崩溃. (第一操作员"将引发异常.您需要保证名称存在,或者分两个步骤进行操作.

Its important to note, that this will crash if the name you pass it does not exist. (The First Operator will throw an exception. You would need to either guarantee that the name exists, or do it in two steps.

如果要一步一步做,就可以做到这一点:(请注意会回来什么)

If you want to do it in one step it comes down to this:(please note what is coming back)

http://odata.netflix.com/catalog/People()?$filter=Name eq 'George Lucas'&$top=1&$expand=TitlesActedIn

您需要扩展,否则它将在.First()之后退出评估,因为TitlesActedIn将为空.

You need the expand or it will quit evaluating after the .First(), because TitlesActedIn will be empty.

它基本上可以翻译为选择Person,包括(扩展)TitlesActedIn关联,然后选择名称(客户端)

It basically translates to select the Person, include (expand) the TitlesActedIn association, then select the name (client side)

这样做的缺点是您要从标题"表中撤回所有内容(所有字段).因此,对于与该人员相关的每个标题,它都会返回(标题,年份,描述,简称等).

The downside of this is that you are pulling back everything (all fields) from the Titles table. So for every title associated to the Person it is returning (Title, Year, Description, ShortName, etc).

如果您在两个查询中都这样做,则只能从TitlesActedIn关联中拉回"ShortName".

If you did this in two queries you could only pull back "ShortName" from the TitlesActedIn association.

这篇关于Linq查询错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆