Returning a single value with Linq to SQL(使用 Linq to SQL 返回单个值)
问题描述
我正在学习 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.
这篇关于使用 Linq to SQL 返回单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Linq to SQL 返回单个值


- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01