Linq异常:函数只能从linq调用到实体 [英] Linq Exception: Function can only be invoked from linq to entities
问题描述
我有一个StudentReceipts
表,其中将ReceiptNo
存储为string(001,002,003,..,099,..)
.
I have a StudentReceipts
table which stores ReceiptNo
as string(001,002,003,..,099,..)
.
我想获取最后的收据编号,以便增加下一笔交易的收据编号.
I want go get the last receiptno details inorder to increment the receiptno for next transaction.
这是我尝试过的
var _lastGeneratedRecDetails = _db.StudentReceipts
.AsEnumerable()
.Where(r => r.Status == true
&& EntityFunctions.TruncateTime(r.DueDate.Value) >= _startDate.Date
&& EntityFunctions.TruncateTime(r.DueDate.Value) <= _endDate.Date)
.OrderByDescending(x => Int32.Parse(x.ReceiptNo))
.FirstOrDefault();
但是我遇到了以下异常
此函数只能从linq调用到实体
this function can only be invoked from linq to entities
任何帮助将不胜感激.
推荐答案
通过调用.AsEnumerable()
,您将从Linq-To-Entities转到Linq-To-Object.通过调用它,还可以过滤内存中的所有结果,因此,每次查询执行通过.AsEnumerable()
方法时,您都会从数据库中提取整个StudentReceipts
表.一般规则是尝试在数据库方面尽力而为:
By calling .AsEnumerable()
you are going from Linq-To-Entities to Linq-To-Object. By calling it, you are also filtering all the results in memory, so you are pulling the whole StudentReceipts
table from the database everytime you do that query as it gets executed past the .AsEnumerable()
method. The general rule is to try to do as much as you can on the database side:
var _lastGeneratedRecDetails =
_db.StudentReceipts.Where(r => r.Status == true
&& EntityFunctions.TruncateTime(r.DueDate.Value) >= _startDate.Date
&& EntityFunctions.TruncateTime(r.DueDate.Value) <= _endDate.Date)
.AsEnumerable()
.OrderByDescending(x => Int32.Parse(x.ReceiptNo))
.FirstOrDefault();
如果您这样做,将过滤数据库中的所有内容并获取过滤的结果.我不知道x.ReceiptNo
是什么类型,但是Linq-To-Entities中不允许调用Int.Parse
.您可以先进行过滤,然后调用AsEnumerable
以便能够在内存中进行解析和排序.
If you do it like this, you will filter everything in the database and fetch the filtered results. I don't know what type x.ReceiptNo
is though, but calling Int.Parse
isn't allowed in Linq-To-Entities. You can filter first and then call AsEnumerable
to be able to do the parsing and ordering in memory.
这篇关于Linq异常:函数只能从linq调用到实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!