繁体   English   中英

ASP.NET Core MVC 1.3 Web API + Entity Framework,我无法按名称搜索数据库,但可以按 ID

[英]ASP.NET Core MVC 1.3 Web API + Entity Framework, I can't search a database by name, but I can by 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; }
    }
}

然后在我的 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();
}

该接口中定义了函数:

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),通过(字符串名称)和后者我寻找

GET /api/hotels/hotel1

它总是返回 404。

这是我基本上改变的

Controller

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)

您必须将路由配置属性放在操作方法上,或者您必须更改路由配置中的路由。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM