[英]ASP.NET Core MVC 1.3 Web API + Entity Framework, I can't search a database by name, but I can by id
I'm an absolute beginner with .NET and I'm unable to fix this.我是 .NET 的绝对初学者,我无法解决这个问题。
Currently I have this:目前我有这个:
Hotel.cs (Model) Hotel.cs(模型)
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Hotels.Models
{
public class Hotel
{
[Key]
public int Id { get; set; }
[Required]
public string name { get; set; }
[Required]
public string city { get; set; }
[Required]
public string image { get; set; }
[Required]
public string category { get; set; }
[Required]
public string description { get; set; }
[Required]
public string features { get; set; }
public bool featured {get; set; }
}
}
Then in my controller I have a function that searches an hotel by its id然后在我的 controller 中,我有一个 function,它按 id 搜索酒店
[HttpGet("{id}",Name="GetHotelById")]
public ActionResult<HotelReadDto> GetHotelById(int id)
{
var hotelItem = _repository.GetHotelById(id);
if(hotelItem != null)
{
return Ok(_mapper.Map<HotelReadDto>(hotelItem));
}
return NotFound();
}
The functions are defined in this interface:该接口中定义了函数:
using System.Collections.Generic;
using Hotels.Models;
namespace Hotels.Data
{
public interface IHotelsRepo
{
bool SaveChanges();
IEnumerable<Hotel> GetAllHotels();
Hotel GetHotelById(int id);
void UpdateHotel(Hotel cmd);
}
}
And this is where the interface is implemented这是实现接口的地方
public Hotel GetHotelById(int id)
{
return _context.Hotels.FirstOrDefault(p => p.Id == id);
}
Right now if I search by id, for example现在,如果我按 id 搜索,例如
GET /api/hotels/1
it returns a value.它返回一个值。
If in all the above functions I change (int id), by (string name) and latter on I look for如果在上述所有函数中我更改了(int id),通过(字符串名称)和后者我寻找
GET /api/hotels/hotel1
It always returns a 404.它总是返回 404。
This is what I basically change这是我基本上改变的
Controller Controller
public ActionResult<HotelReadDto> GetHotelById(string name)
{
var hotelItem = _repository.GetHotelById(string name);
if (hotelItem != null)
{
return Ok(_mapper.Map<HotelReadDto>(hotelItem));
}
return NotFound();
}
Interface界面
Hotel GetHotelById(string name);
And then the repo然后回购
public Hotel GetHotelById(string name)
{
return _context.Hotels.FirstOrDefault(p => p.name == name);
}
But it still returns a 404, I'm a bit lost with how could I change it to look for name instead of id但它仍然返回 404,我有点迷茫,我怎么能改变它来寻找名字而不是 id
Is the attribute above the method still the following?方法上面的属性还是下面的吗?
[HttpGet("{id}",Name="GetHotelById")]
public ActionResult<HotelReadDto> GetHotelById(string name)
If so, try changing it to this:如果是这样,请尝试将其更改为:
[HttpGet("{name}",Name="GetHotelById")]
public ActionResult<HotelReadDto> GetHotelById(string name)
You have to put route config attribute on action method or you have to change the route in route config.您必须将路由配置属性放在操作方法上,或者您必须更改路由配置中的路由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.