[英]Search by name instead of id
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. 我正在学习Asp.net Web api 2.0,当前的CRUD方法只是按ID搜索,因此我试图按书名进行搜索,但未成功。
What I added to the WebApiConfig.cs
: 我添加到
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'.
但是,这会让我在尝试运行LINQ查询的那一行上建立此错误:
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();
我试图将查询更改为
Book book = db.Books.Where(a => a.Title == name).AsQueryable();
but I still get the same error. 但我仍然遇到相同的错误。
It returns a result set of IQueryable . 它返回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 或者,如果只需要第一个结果集,则可以使用FirstoreDefault
Book book = db.Books.FirstOrDefault(a => a.Title == name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.