Cannot Implicitly convert type System.Linq.IQueryable<AnonymousType#1> to System.Linq.IQueryable<AnonymousType#2>

I have a query that works perfectly when I put everything in one statement:

var rs = db.SerialNumbers
  .Join(db.ProductLines, sn => sn.ProductLineId, pl => pl.Id, (sn, pl) => new { pl.Id, pl.Category, sn.UserId })
  .Where(sn => sn.UserId == userId)
  .Select(sn => new { sn.Id, sn.Category })
  .Distinct();

But I need to add condition to the UserId. I only want to filter if there's an entry in the userId, ie userId > 0. So I change to query to:

 var rs = db.SerialNumbers
   .Join(db.ProductLines, sn => sn.ProductLineId, pl => pl.Id, (sn, pl) => new { pl.Id, pl.Category, sn.UserId });

  if(userId > 0)
  {
    rs = rs.Where(sn => sn.UserId == userId);
  }

  rs = rs.Select(sn => new { sn.Id, sn.Category });

I get this error on compile:

Cannot Implicitly convert type System.Linq.IQueryable<AnonymousType#1> to System.Linq.IQueryable<AnonymousType#2>

What should I do?

Jon Skeet
people
quotationmark

Your join projects to this:

(sn, pl) => new { pl.Id, pl.Category, sn.UserId }

But your final assignment is to this:

sn => new { sn.Id, sn.Category }

They're not the same type, hence the problem.

If the query is actually already in the shape that you want, the simplest fix is just to use two different variables:

var query = db.SerialNumbers
              .Join(db.ProductLines,
                    sn => sn.ProductLineId,
                    pl => pl.Id,
                    (sn, pl) => new { pl.Id, pl.Category, sn.UserId });
if (userId > 0)
{
      query = query.Where(sn => sn.UserId == userId);
}
var results = query.Select(sn => new { sn.Id, sn.Category });

people

See more on this question at Stackoverflow