简体   繁体   中英

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' . 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. Is there a way to do that?

No, the problem is that the result is a sequence whereas your variable is a single 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() :

     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.

  • 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() .

The LINQ query returns a set ( IEnumerable<T> ) of ItemTaxonomy objects, which you are trying to assign to a variable of type ItemTaxonomy .

You need to change the type of the variable to IEnumerable<ItemTaxonomy> . (Or call First() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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