从Db实体返回多个值(实体框架)

时间:2019-02-25 18:26:52

标签: c# asp.net-web-api

我有2个类控制器-房屋和公寓,以及公寓类中的Get方法,该方法返回具有给定ID的房屋中的公寓,这是路线:

[Route("api/house/{houseId}/apartments")]

我有此代码,它返回apartment(单)。问题是,如何使此工作具有不止1个返回结果?如果有多个公寓要退房,当前代码会给出错误消息。

[ResponseType(typeof(Apartment))]
public IHttpActionResult GetApartments(Guid houseId)
{
    Apartment apartment = db.Apartments.SingleOrDefault(user => user.HouseId == houseId);
    if (apartment == null)
    {
        return NotFound();
    }
    return Ok(apartment);
}

2 个答案:

答案 0 :(得分:1)

[ResponseType(typeof(Apartment[]))]
public IHttpActionResult GetApartments(Guid houseId)
{
    var apartments = db.Apartments.Where(user => user.HouseId == houseId).ToList();
    if (!apartments.Any())
    {
        return NotFound();
    }
    return Ok(apartments);
}

使用ToList代替SingleOrDefault

答案 1 :(得分:0)

Apartment apartment = db.Apartments.FirstOrDefault(user => user.HouseId == houseId);

给出第一个或默认结果。

Apartment apartment = db.Apartments.First(user => user.HouseId == houseId);

给出第一个或空结果(如果未找到结果)。

Apartment apartment = new Apartment();
var apts = db.Apartments.Where(user => user.HouseId == houseId).toList();
if (apts.Any()) apartment = apts[0];

获取列表的第一个结果。