使用LINQ返回一个值到SQL [英] Returning a single value with Linq to SQL
问题描述
我在学习LINQ to SQL和我无法抓住它。我想简单地返回在C#单(布尔)值与LINQ查询。
我想看看故事的主人想在添加新的评论发送电子邮件通知。我想包含LINQ到SQL该方法返回一个布尔值。
公共BOOL NotifyOnComment(用户名字符串){
VAR通知=(从s在db.AccountSettings
其中,s.UserName ==用户名
选择s.NotifyOnComment).DefaultIfEmpty(假); //无能
}
更新:
我做的,现在以下内容:
VAR通知=(从s在db.AccountSettings
其中,s.UserName ==用户名
选择s.NotifyOnComment).SingleOrDefault(); 返回(布尔)通知;
LINQ中,默认情况下总是返回集合。如果你需要一个值,你可以将 。单()
, .SingleOrDefault()
或 。首先()
或 .FirstOrDefault()
一>方法。
他们他们做了什么略有不同。 单()
和的SingleOrDefault()
如果只会工作的究竟或最多的结果中的一个记录。 第一()
和 FirstOrDefault()
将工作,即使有更多的结果。
的 * OrDefault()
变种将返回的情况下,该类型的结果包含任何记录的默认值。
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.
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
}
Update:
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, by default always returns collections. If you need a single value, you can apply the .Single()
, .SingleOrDefault()
or .First()
or .FirstOrDefault()
methods.
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.
The *OrDefault()
variants will return the default value for the type in case the result contained no records.
这篇关于使用LINQ返回一个值到SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!