Linq to NHibernate:序列不包含元素
我知道我在这里做错了什么,我只是不知道是什么,因为我不太确定问题是什么。下面是调用的代码:
调用
System.Linq.Expressions.Expression<Func<AccountDataModel, bool>> deleg =
(m => m.Email == model.Email);
AccountDataModel query = database.FindBy(deleg);
调用导致的位置
public T FindBy(Expression<Func<T, bool>> expression)
{
return FilterBy(expression).Single();
}
public IQueryable<T> FilterBy(Expression<Func<T, bool>> expression)
{
return All().Where(expression).AsQueryable();
}
public IQueryable<T> All()
{
return (from data in _session.Query<T>()
select data);
}
抛出的异常
Sequence contains no elements
详细信息
基本上,什么我现在正在尝试测试我网站上的一个注册模块,该模块应该搜索已提供的电子邮件以查看其是否存在。我在数据库中隐藏了一个加密的电子邮件地址(是的,模型中的电子邮件也已加密),该地址应该与提供的注册电子邮件相匹配。问题是没有返回任何结果。
我到底做错了什么?
I know I'm doing something wrong here, I just don't know what as I'm not very sure what the issue is. Here's the code which is called:
The call
System.Linq.Expressions.Expression<Func<AccountDataModel, bool>> deleg =
(m => m.Email == model.Email);
AccountDataModel query = database.FindBy(deleg);
Where the call leads to
public T FindBy(Expression<Func<T, bool>> expression)
{
return FilterBy(expression).Single();
}
public IQueryable<T> FilterBy(Expression<Func<T, bool>> expression)
{
return All().Where(expression).AsQueryable();
}
public IQueryable<T> All()
{
return (from data in _session.Query<T>()
select data);
}
The exception thrown
Sequence contains no elements
Ze details
Basically, what I'm trying to test right now is a registration module on my website which is supposed to search for an email which has been provided to see if it exists. I have an encrypted email address hidden in the database (and, yes, the email in the model has been encrypted as well) which is supposed to match up with the registration email provided. The problem is that no results are being returned.
What exactly am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当序列为空时,对
.Single
的调用将引发此异常。如果可能找不到匹配项,则应使用.SingleOrDefault
,如果不存在匹配项,它将返回null
。了解
Single
、SingleOrDefault
、First
和FirstOrDefault
之间的差异非常重要。下面是这些方法的有用可视化:
如您所见,
FirstOrDefault
是唯一不会引发异常的方法。所以,归根结底是这样的:
使用
First
、SingleOrDefault
或Single
的唯一原因是,如果结果不符合您的预期,则会抛出异常!这将为您提供更好的调试体验,并为您的代码提供更好的语义。
Your call to
.Single
will throw this exception when the sequence is empty. If it is possible that no matches will be found, you should use.SingleOrDefault
, which will returnnull
if no matches exist.It's very important to Understand the differences between
Single
,SingleOrDefault
,First
, andFirstOrDefault
.Here's a helpful visualization of these methods:
As you can see,
FirstOrDefault
is the only one that won't throw an exception.So, what it comes down to is this:
The ONLY reason to use
First
,SingleOrDefault
, orSingle
, is so that an Exception will be thrown if your results are not as you expect!This will give you a better debugging experience, and gives your code better semantic meaning.