[ad_1]
I'm using some free source code to create an e-commerce site in WebForms. It is the Visual Basic version of Getting Started with ASP.NET 4.5 Web Forms and Visual Studio 2013. I have been successful until I coded the ProductDetails.aspx.vb page. I replaced my object names and properties accordingly, but when I run the project, I get this error: Unable to cast object of type 'WhereEnumerableIterator`1[LethalLibrary.Book]' to type 'System.Linq.IQueryable`1[LethalLibrary.Book]'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'WhereEnumerableIterator`1[LethalLibrary.Book]' to type 'System.Linq.IQueryable`1[LethalLibrary.Book]'. Does Linq from VS2017 differ from VS2013? How do I fix this?
我尝试过的:
VB
Public Function GetBook(<QueryString("BookID")> BookId As Nullable(Of Integer)) As IQueryable(Of Book) Dim db = New BookContext() Dim query As IQueryable(Of Book) = db.Books If BookId.HasValue AndAlso BookId > 0 Then query = query.Where(CType(Function(p) p.BookID = BookId, Func(Of Book, Boolean))) ElseIf Not String.IsNullOrEmpty(BookTitle) Then query = query.Where(Function(p) String.Compare(p.BookTitle, BookTitle) = 0) Else query = Nothing End If Return query End Function
我还添加了
VB
.Select(Function(p) p)
到我的 .Where 语句的末尾,但这也不起作用。
VB
<pre>Public Function GetBook(<QueryString("BookID")> BookId As Nullable(Of Integer)) As IQueryable(Of Book) Dim db = New BookContext() Dim query As IQueryable(Of Book) = db.Books If BookId.HasValue AndAlso BookId > 0 Then query = query.Where(CType(Function(p) p.BookID = BookId, Func(Of Book, Boolean))).Select(Function(p) p) Else query = Nothing End If Return query End Function
解决方案1
尝试使用 Enumerable.Cast(TResult) 方法 (IEnumerable) (System.Linq)[^] :
网络
Dim query As IQueryable(Of Book) = db.Books.Cast(Of Book)() _ .Where(Function(x) x.BookID = BookId) _ .ToList()
或者 Enumerable.OfType(TResult) 方法 (IEnumerable) (System.Linq)[^]:
网络
Dim query As IQueryable(Of Book) = db.Books.OfType(Of Book)() _ .Where(Function(x) x.BookID = BookId) _ .ToList()
欲了解更多详情,请参阅: 支持和不支持的 LINQ 方法 (LINQ to Entities) | 微软文档[^]
解决方案2
我在 ASP.NET 论坛上找到了解决方案; 我添加了 AsQueryable()
到我的结束 query
变量并且它起作用了!
VB
Public Function GetBook(BookId As Nullable(Of Integer)) As IQueryable(Of Book) Dim BookTitle As String = "aaaa" Dim db = New ApplicationDbContext() Dim query As IQueryable(Of Book) = db.Books If BookId.HasValue AndAlso BookId > 0 Then query = (query.Where(CType(Function(p) p.BookId = BookId, Func(Of Book, Boolean)))).AsQueryable() ElseIf Not String.IsNullOrEmpty(BookTitle) Then query = (query.Where(Function(p) String.Compare(p.BookTitle, BookTitle) = 0)).AsQueryable() Else query = Nothing End If Return query End Function
解决方案3
AsQueryable 也为我工作(在 cSharp 中)
谢谢
[ad_2]
コメント