使用 Linq to SQL 返回单个值
- 作者: 别鸡眼我愿意闹
- 来源: 51数据库
- 2022-12-08
问题描述
我正在学习 Linq to SQL,但无法掌握它.我正在尝试使用 Linq 查询在 C# 中简单地返回单个(布尔值)值.
I'm learning Linq to SQL and I'm having trouble grasping it. I'm trying to simply return a single (boolean) value in C# with a Linq query.
我想看看故事的所有者是否希望在添加新评论时发送电子邮件通知.我希望包含 Linq to SQL 的方法返回一个布尔值.
I want to see if the owner of a story would like an email notification sent when new comments are added. I would like the method that contains the Linq to SQL to return a boolean value.
public bool NotifyOnComment(string username){
var notify = (from s in db.AccountSettings
where s.UserName == username
select s.NotifyOnComment).DefaultIfEmpty(false);
// clueless
}
更新:
我现在正在做以下事情:
I'm doing the following now:
var notify = (from s in db.AccountSettings
where s.UserName == username
select s.NotifyOnComment).SingleOrDefault();
return (bool)notify;
推荐答案
Linq,默认总是返回集合.如果您需要单个值,您可以应用 .Single(), .SingleOrDefault() 或 .First() 或 .FirstOrDefault() 方法.
Linq, by default always returns collections. If you need a single value, you can apply the .Single(), .SingleOrDefault() or .First() or .FirstOrDefault() methods.
他们在做什么方面略有不同.Single() 和 SingleOrDefault() 仅在结果中有恰好或最多条记录时有效.First() 和 FirstOrDefault() 会起作用,即使有更多的结果.
They differ slightly in what they do. Single() and SingleOrDefault() will only work if there is exactly or at most one record in the result. First() and FirstOrDefault() will work, even if there are more results.
如果结果不包含记录,*OrDefault() 变体将返回类型的默认值.
The *OrDefault() variants will return the default value for the type in case the result contained no records.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
