简体   繁体   中英

C# : How to get anonymous type from LINQ result

I need to get NewsImage field and list of categories Ids that associated with the news in Many to Many relationship ... but it gives me error:

The type of one of the expressions in the join clause is incorrect.Type inference failed in the call to 'Join'.

My code looks like this

  var Result1 = (from c in db.News
                   join d in db.Categories
                on c.NewsId equals d.News.Select(l => l.NewsId)
                   where c.NewsId == 1
                   select new { c.NewsImagePath, d.CategoryId }).ToList();

The problem is inside the on statement.

on c.NewsId equals d.News.Select( l => l.NewsId )

The Select on the right-hand side will return a IEnumerable of news, which is not what you want.

Something like this would technically work:

on c.NewsId equals d.News.Select( l => l.NewsId ).FirstOrDefault()

But it does not make sense logically.

I suspect the whole query should be built differently. I think you want to join when the category list of news contains the news item. In that case, you can't use the join statement, it would look somewhat like this:

from n in db.News
from c in db.Categories
where c.News.Select( ne => ne.NewsId ).Contains( n.NewsId )
select new { n.NewsImagePath, c.CategoryId }

Assuming you have a navigation property defining the nn relation I would write:

var result = db.News
  .Where(x => x.NewsId == 1)
  .SelectMany(x => x.Categories, 
              (news, category) => new { news.NewsImagePath, category.CategoryId })
  .ToList();

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