无法将类型整数隐式转换为bool

时间:2014-05-17 11:35:17

标签: c# asp.net-mvc linq

希望你能帮我解决这个问题。我搜索了之前提出的问题,但是     用提供的答案无法解决这个问题。     我在where子句中收到错误“无法将类型整数隐式转换为bool”。     这一刻     我的数据库中的SchoolMasterID列和通过构造函数提供的Id两者     具有整数类型。

public List<SchoolmasterIndexView> GetdSchoolMaster(EduDbContext db, int Id)
{
   var _schoolmaster = from n in db.SchoolMasters
   join c in db.Address on n.AddressID equals c.AddressID
   where **n.SchoolMasterID = Id**
   orderby n.SchoolMasterName
   select new SchoolmasterIndexView()
   {
      SchoolMasterID = n.SchoolMasterID,
      SchoolMasterName = n.SchoolMasterName,
      AddressID = c.AddressID,
      AddressLine1 = c.AddressLine1,
      AddressLine2 = c.AddressLine2,
      PostalCode = c.PostalCode,
      City = c.City
                   };
      return _schoolmaster.ToList();
    }
}

1 个答案:

答案 0 :(得分:8)

您需要在where子句中使用等于运算符==而不是赋值运算符=

var _schoolmaster = from n in db.SchoolMasters
                    join c in db.Address on n.AddressID equals c.AddressID
                    where n.SchoolMasterID == Id //<--equality operator
                    orderby n.SchoolMasterName
                    ...

考虑下一个简单的代码:

from item in new []{1,2,3} //array of ints
where item = 2             //compilation error, because of assignment operator
select item;

编译器触发完全相同的错误Cannot implicitly convert type 'int' to 'bool'

出现此错误,因为赋值运算符返回指定的值。例如:

int a;
var b = a = 2; //result of "a = 2" expression is 2 and then assigned to b 

Console.WriteLine(b); //prints 2. Two variables both have value 2

在Linq where子句中需要bool,但会获得int类型。这就是编译器抱怨的原因,它无法将int转换为bool