[英]using .SingleOrDefault() inside .Where() will raise the following exception:- System.NotSupportedException was unhandled by user code
I am working on an asp.net mvc-4 web application, and i am using Entity Framework 5. now i have the following model method:- 我正在开发一个asp.net mvc-4 Web应用程序,并且正在使用Entity Framework5。现在我具有以下模型方法:
public IQueryable<TMSStorageDevice> CustomerSD(int customerid)
{
var customerSiteIds = entities.SiteDefinitions.Where(a => a.AccountDefinitions1.SingleOrDefault().ORG_ID == customerid).Select(a2 => a2.SITEID).ToList();
}
now this will raise the following error:- 现在,这将引发以下错误:
System.NotSupportedException was unhandled by user code
HResult=-2146233067
Message=The methods 'Single' and 'SingleOrDefault' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.
Source=System.Data.Entity
StackTrace:
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SingleTranslatorBase.TranslateUnary(ExpressionConverter parent, DbExpression operand, MethodCallExpression call)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.UnarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Objects.ELinq.ExpressionConver
i was able to fix this by replacing ( SingleOrDefault()
):- 我能够通过替换(
SingleOrDefault()
)来解决此问题:
a.AccountDefinitions1.SingleOrDefault().ORG_ID
with ( FirstOrDefault()
):- 与(
FirstOrDefault()
):-
a.AccountDefinitions1.FirsteOrDefault().ORG_ID
so can anyone advice on this behavior ? 那么任何人都可以对此行为提出建议吗? i mean why
FirstOrDefault()
will work in this case unlike SingleorDefault()
? 我的意思是,为什么
FirstOrDefault()
在这种情况下可以与SingleorDefault()
不同?
Because SingleOrDefault
would require it to generate SQL which ensures that there is not more than 1 foreign row. 因为
SingleOrDefault
将要求它生成SQL,以确保不超过1个外部行。 Essentially, it would have to create a join which returns no rows if the count > 1 本质上,如果count> 1,则必须创建一个不返回任何行的联接
FirstOrDefault
, however, simply allows it to generate a join and SELECT TOP 1
(or equivalent) which is vastly easier. 但是,
FirstOrDefault
只是简单地允许它生成FirstOrDefault
和SELECT TOP 1
(或等效的选择),因此非常容易。
It just simply isn't implemented in EF. 它只是根本没有在EF中实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.