Apartment model
public long Id { get; set; }
public int ApartmentNumber { get; set; }
public int FloorNumber { get; set; }
public int NumberofRooms { get; set; }
public int NumberofResidents { get; set; }
public decimal FullArea { get; set; }
public decimal LivingSpace { get; set; }
public long HouseId { get; set; }
public House House { get; set; }
public ICollection<Tenant> Tenants { get; set; }
House model
public long Id { get; set; }
public int Number { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Postcode { get; set; }
public ICollection<Apartment> Apartments { get; set; }
I understand that in order for it to be available at "/api/house/{houseId}/apartments" you need to add [Route], right? But I don’t fully understand how to make it return the apartments of a specific house by the Id of the house. And in which controller this method should be located?
[Route("/api/house/{houseId}/apartments")]
[HttpGet("{id}")]
public async Task<ActionResult<Apartment>> GetApartment(long id)
{
var HouseId= await _context.Apartments.FindAsync(id);
if (HouseId == null)
{
return NotFound();
}
return HouseId;
}
CodePudding user response:
Modify your api as below:
[Route("/api/house/{houseId}/apartments")]
[HttpGet]
public ActionResult<Apartment> GetApartment(int houseId)
{
return Ok();
}
You could pass the houseid to controller now, And you could try the below codes in controller:
var targetapartments= await _context.Apartments.Where(x.HouseId==houseId).ToList();
CodePudding user response:
This is how your controller could look like:
[ApiController]
[Route("api/[controller]")]
public class HouseController : ControllerBase
{
[HttpGet("{houseId}/apartments")]
public async Task<ActionResult<IEnumerable<Apartment>>> GetApartments(int houseId)
{
var house = await _context.Houses
.Include(house => house.Apartments)
.FirstOrDefaultAsync(house => house.Id == houseId);
if (house == null)
{
return NotFound();
}
return house.Apartments;
}
}