I'm learning the Asp.net web api 2.0 and the current CRUD method just searches by id so I attempted to make it search by a title of a book but I've been unsuccessful.
What I added to the WebApiConfig.cs
:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{name}",
defaults: new { name = RouteParameter.Optional }
};
And the part I'm having trouble with:
// GET: api/Books/Name
[ResponseType(typeof(Book))]
public IHttpActionResult GetBook(string name)
{
Book book = from a in db.Books where a.Title == name select a;
if (book == null)
{
return NotFound();
}
else
{
return Ok(book);
}
}
However it would let me build this, on the line where I'm trying to run the LINQ query I get an error of: Cannot implicitly convert type 'System.Linq.IQueryable<BookService.Models.Book>'to 'BookService.Models.Book'.
I tried changing the query around to be Book book = db.Books.Where(a => a.Title == name).AsQueryable();
but I still get the same error.
It returns a result set of IQueryable . Change
Book book = from a in db.Books where a.Title == name select a;
to
var books = from a in db.Books where a.Title == name select a;
and then you need to iterate on the result set.
Or if you only need the first result set then you can use FirstoreDefault
Book book = db.Books.FirstOrDefault(a => a.Title == name);
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.