简体   繁体   English

LINQ加入仅适用于Orderby

[英]LINQ Join for Orderby only

I am trying to run this code: 我正在尝试运行以下代码:

ItemTaxonomy iTaxonomy = from itemTaxonomy in connection.ItemTaxonomy
                         where itemTaxonomy.Item.ID == itemView.ID
                         orderby itemTaxonomy.Taxonomy.Name
                         select itemTaxonomy;

When I compiled it I get the error: 当我编译它时,出现错误:

Cannot implicitly convert type 'System.Linq.IOrderedQueryable<Website.Models.ItemTaxonomy>' to 'Website.Models.ItemTaxonomy' . 无法将类型'System.Linq.IOrderedQueryable<Website.Models.ItemTaxonomy>'隐式转换为'Website.Models.ItemTaxonomy' An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)

I believe the issue is with orderby itemTaxonomy.Taxonomy.Name but I am just trying to order by the name of Taxonomy items instead of their IDs. 我相信问题在于orderby itemTaxonomy.Taxonomy.Name但我只是想按分类项目的名称而不是其ID进行订购。 Is there a way to do that? 有没有办法做到这一点?

No, the problem is that the result is a sequence whereas your variable is a single item . 不,问题在于结果是序列,而变量是单个item

Given that you're expressing ordering, you must be expecting multiple values - so what do you want to do with them? 鉴于您要表达排序,您必须期待多个值-那么您想对它们做什么? Options: 选项:

  • Use First() : 使用First()

     ItemTaxonomy iTaxonomy = (from itemTaxonomy in connection.ItemTaxonomy where itemTaxonomy.Item.ID == itemView.ID orderby itemTaxonomy.Taxonomy.Name select itemTaxonomy).First(); 

    This will return the ItemTaxonomy with the earliest name out of all the ones with the appropriate item ID. 这将返回具有适当项目ID的所有项目中名称最早的ItemTaxonomy

  • Change your variable type: 更改变量类型:

     IEnumerable<ItemTaxonomy> taxonomies = from itemTaxonomy in connection.ItemTaxonomy where itemTaxonomy.Item.ID == itemView.ID orderby itemTaxonomy.Taxonomy.Name select itemTaxonomy; 

    Now you've got a sequence of taxonomies to deal with, instead of a single item. 现在,您需要处理一系列分类法,而不是单个项目。

You seem to be capturing a single value from a query . 您似乎正在从查询中捕获单个值。 Try: 尝试:

var iTaxonomy = from itemTaxonomy in connection.ItemTaxonomy
                where itemTaxonomy.Item.ID == itemView.ID
                orderby itemTaxonomy.Taxonomy.Name
                select itemTaxonomy;

or to be more explicit: 或更明确地说:

IQueryable<ItemTaxonomy> iTaxonomy = ...

If you do want a single item, use ,First() or .Single() . 如果确实需要单个项目,请使用,First().Single()

The LINQ query returns a set ( IEnumerable<T> ) of ItemTaxonomy objects, which you are trying to assign to a variable of type ItemTaxonomy . LINQ查询返回ItemTaxonomy对象的集合( IEnumerable<T> ),您正在尝试将其分配给ItemTaxonomy类型的变量。

You need to change the type of the variable to IEnumerable<ItemTaxonomy> . 您需要将变量的类型更改为IEnumerable<ItemTaxonomy> (Or call First() ) (或致电First()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM