I want to query to a book in my library database, so I wrote this code...
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Web;
/// <summary>
/// Summary description for Book
/// </summary>
public partial class Book
{
public static List<Book> GetQueryBooks(string query)
{
// Init db
LibraryDataClassesDataContext db = new LibraryDataClassesDataContext();
return db.Books.Where(b => b.Title.Contains(query) || b.Author.Contains(query)).ToList();
}
}
But I do not get why I get a "InvalidCastException: Specified cast is not valid" on the return?
It looks to me like you are missing a namespace - so Book
here (in the class
definition) refers to global::Book
- rather than whatever-your-LINQ-namespace-is Book
. Essentially, then, your partial class Book
is a completely different type to the Book
that the LibraryDataClassesDataContext
knows about.
Try:
namespace The.Correct.Namespace
{
public partial class Book
{
public static List<Book> GetQueryBooks(string query)
{
// Init db
LibraryDataClassesDataContext db = new LibraryDataClassesDataContext();
return db.Books.Where(b => b.Title.Contains(query) || b.Author.Contains(query)).ToList();
}
}
}
where The.Correct.Namespace
is the namespace that LibraryDataClasses.designer.cs
(I'm guessing on the file name here) is using.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.