如何解决ASP.NET Core MVC 1.3 Web API +实体框架,我无法按名称搜索数据库,但可以按ID
我绝对是.NET的初学者,无法解决此问题。
目前我有这个:
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; }
}
}
然后在我的控制器中,我有一个功能可以通过其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();
}
功能在此界面中定义:
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);
}
}
这是实现接口的地方
public Hotel GetHotelById(int id)
{
return _context.Hotels.FirstOrDefault(p => p.Id == id);
}
例如,如果我现在按ID搜索
GET /api/hotels/1
它返回一个值。
如果在上述所有函数中,我都更改了(int id),按(string name)进行了更改,后来我寻找了
GET /api/hotels/hotel1
它总是返回404。
这是我的基本改变
控制器
public ActionResult<HotelReadDto> GetHotelById(string name)
{
var hotelItem = _repository.GetHotelById(string name);
if (hotelItem != null)
{
return Ok(_mapper.Map<HotelReadDto>(hotelItem));
}
return NotFound();
}
接口
Hotel GetHotelById(string name);
然后是仓库
public Hotel GetHotelById(string name)
{
return _context.Hotels.FirstOrDefault(p => p.name == name);
}
但是它仍然返回404,我对如何更改它以查找名称而不是id感到迷茫
解决方法
方法上方的属性是否仍然存在?
[HttpGet("{id}",Name="GetHotelById")]
public ActionResult<HotelReadDto> GetHotelById(string name)
如果是这样,请尝试将其更改为此:
[HttpGet("{name}",Name="GetHotelById")]
public ActionResult<HotelReadDto> GetHotelById(string name)
,
您必须将路由配置属性置于操作方法上,或者必须在路由配置中更改路由。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。