实体框架检查结果为null

时间:2017-10-25 13:42:34

标签: entity-framework linq

我正在使用此查询:

 var result = from r in db.Registrations
              join u in db.UserTypes on r.UserTypeId equals u.UserTypeId
              where r.Email.ToLower()==model.LoginEmail.ToLower() && r.Password.ToLower() == model.Password.ToLower()
              select new { r,u};

如果没有找到记录,我怎么检查?如果是,那么

 if(result == null)
     // no record found
 else
     // record found

2 个答案:

答案 0 :(得分:2)

您可以使用AnyCount扩展程序:

 if(!result.Any())
///norecord found
else
//record found

使用Count将是:

 if(result.Count()==0)
///norecord found
else
//record found

答案 1 :(得分:1)

首先,您为结果分配的只是IQueryable,因此它是查询,您需要先执行它。所以我建议将其重命名为查询,然后执行以下操作:

var query= from r in db.Registrations
           join u in db.UserTypes on r.UserTypeId equals u.UserTypeId
           where r.Email.ToLower()==model.LoginEmail.ToLower() && r.Password.ToLower() == model.Password.ToLower();    
           select new { r,u};

var result = query.FirstOrDefault(); // gives first result or null
if (result == null) {
  // no record
} else {
  // record found and is in result
}