我收到了错误
cannot implicity convert type 'System.Linq.IQueryable<EntityNetimoveis.San_Imovel>' to 'EntityNetimoveis.San_Imovel' An Explicit conversion exists (are you missing a cast ?)
当我尝试以下代码时会发生这种情况
EntityNetimoveis.San2011Entities db = new EntityNetimoveis.San2011Entities();
EntityNetimoveis.San_Imovel im = db.San_Imovel.Where(a => a.Credenciada_Id == 10);
我必须做什么类型的转换?
答案 0 :(得分:3)
EntityNetimoveis.San_Imovel im = db.San_Imovel.Where(a => a.Credenciada_Id == 10);
im的类型是IQueryable<EntityNetimoveis.San_Imovel>
,因为您正在运行where查询,并且可能有多个结果。如果您希望第一个结果与您的查询匹配,则应使用.FirstOrDefault()。尝试将代码更改为:
EntityNetimoveis.San_Imovel im = db.San_Imovel.FirstOrDefault(a => a.Credenciada_Id == 10);
如果要返回多个实体并处理它们,假设使用foreach循环,则需要将返回值的类型更改为IEnumerable<Netimoveis.San_Imovel>
。请参阅以下示例:
IEnumerable<EntityNetimoveis.San_Imovel> ims = db.San_Imovel.Where(a => a.Credenciada_Id == 10);
您可以使用以下内容:
foreach(var im in ims) {
// your code goes here
}
答案 1 :(得分:2)
如果lambda可以返回多个记录:
var imList = db.San_Imovel.Where(a => a.Credenciada_Id == 10).ToList();