无法将System.Linq.IQueryable <AnonymousType#1>类型隐式转换为System.Linq.IQueryable <AnonymousType#2>

Eri*_*ric 1 linq entity-framework asp.net-mvc-4

当我将所有内容放在一个语句中时,我有一个完美的查询:

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();
Run Code Online (Sandbox Code Playgroud)

但是我需要为UserId添加条件.我只想过滤userId中是否有条目,即userId> 0.所以我改为查询:

 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 });
Run Code Online (Sandbox Code Playgroud)

我在编译时遇到这个错误:

无法将类型隐式转换System.Linq.IQueryable<AnonymousType#1>System.Linq.IQueryable<AnonymousType#2>

我该怎么办?

Jon*_*eet 5

您的加入项目:

(sn, pl) => new { pl.Id, pl.Category, sn.UserId }
Run Code Online (Sandbox Code Playgroud)

但你最后的任务是:

sn => new { sn.Id, sn.Category }
Run Code Online (Sandbox Code Playgroud)

他们不是同一类型,因此问题.

如果查询实际上已经是您想要的形状,最简单的解决方法就是使用两个不同的变量:

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 });
Run Code Online (Sandbox Code Playgroud)