Below is an example that transforms the stored procedure result set List<Hotel> to an a type, HotelData, that best fits the JSON format.
Models
public class Hotel
{
public int Id { get; set; }
public int HotelStaffCount { get; set; }
public int HotelCertificateCode { get; set; }
public string HotelName { get; set; }
public int HotelCode { get; set; }
}
public class HotelData
{
public string[] Name { get; set; }
public List<Value> Value { get; set; }
}
public class Value
{
public string names { get; set; }
public int[] data { get; set; }
}
Service that does the model conversion.
public interface IHotelService
{
Task<HotelData> GetHotelDetails();
}
public class HotelService : IHotelService
{
private readonly SqliteContext _context;
public HotelService(SqliteContext context)
{
_context = context;
}
public async Task<HotelData> GetHotelDetails()
{
//Get the data
List<Hotel> results = await _context.Hotel.ToListAsync();
List<Value> values = new List<Value>();
//Convert the Hotel obejct to HotelData to get the correct JSON
int[] codes = results.Select(s => s.HotelCode).Distinct().ToArray();
foreach (int code in codes)
{
values.Add(GetValueById(results, code));
}
HotelData data = new HotelData()
{
Name = results.Select(s => s.HotelName).Distinct().ToArray(),
Value = values
};
return data;
}
private Value GetValueById(List<Hotel> records, int code)
{
return new Value()
{
names = $"hotel certificate code {code}",
data = records.Where(c => c.HotelCertificateCode == code).Select(s => s.HotelStaffCount).ToArray()
};
}
}
Web API Action
[Route("api/[controller]")]
[ApiController]
public class HotelController : ControllerBase
{
private readonly ILogger<HotelController> _logger;
private readonly IHotelService _hotelService;
public HotelController(ILogger<HotelController> logger, IHotelService hotelService)
{
_logger = logger;
_hotelService = hotelService;
}
[HttpGet]
public async Task<IActionResult> Get()
{
HotelData data = await _hotelService.GetHotelDetails();
return Ok(data);
}
}
Results
{
"name": [
"black ins hotel",
"white ins hotel"
],
"value": [
{
"names": "hotel certificate code 1",
"data": [
100,
45
]
},
{
"names": "hotel certificate code 2",
"data": [
23,
55
]
}
]
}
The .NET 5/6 tutorials on this site to are very good for learning the basics.
https://learn.microsoft.com/en-us/aspnet/core/tutorials/choose-web-ui?view=aspnetcore-6.0
