假设查询中有5条记录,如何获得前1条记录?这是我目前的代码.
public Application GetByUserIdAndVersion(int userId, string version)
{
VettingDataContext dc = new VettingDataContext(_connString);
return (from a in dc.Applications
where a.UserId == userId && a.chr_Version == version
select a).SingleOrDefault<Application>();
}
Run Code Online (Sandbox Code Playgroud)
只需使用FirstOrDefault():
return (from a in dc.Applications
where a.UserId == userId && a.chr_Version == version
select a).FirstOrDefault<Application>();
Run Code Online (Sandbox Code Playgroud)
SingleOrDefault()如果有多个记录,则会抛出异常,FirstOrDefault()只会占用第一个记录.
此外,你不应该强制转换Application- 你的记录已经是类型Application.