2016-03-15 97 views
2

我有,当我把一切都在一个声明中完美的作品查询:不能隐式转换类型System.Linq.IQueryable <AnonymousType#1> System.Linq.IQueryable <AnonymousType#2>

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(); 

但是我需要为UserId添加条件。我只想过滤,如果有一个在用户id的条目,即用户ID> 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 }); 

我得到的编译此错误:

不能隐式转换类型System.Linq.IQueryable<AnonymousType#1>System.Linq.IQueryable<AnonymousType#2>

我该怎么办?

回答

5

你加入项目,这一点:

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

但最终分配是这样的:

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

他们是不是同一类型,因此这个问题。

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

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 });