I'm doing a webApi, which has its entities and its context class that it creates through the database, with its respective command.
Everything is working perfectly for me, the drama is when I want to return a set of objects in JSON and it only returns one.
I have a context class, which makes dependency injections for all entities.
If in my [HttpGet] I do this:
public IEnumerable<Sucursales> Get()
{
using (var _context = new hn_asis_testContext())
{
return _context.Sucursales.ToList();
}
}
Return this to me:
[
{
"sucursalId": 2,
"nombre": "Santa Clara",
"barrioId": 1,
"empleados": [
],
"ventas": [
],
"barrio": null
},
{
"sucursalId": 3,
"nombre": "Santa Clara",
"barrioId": 1,
"empleados": [
],
"ventas": [
],
"barrio": null
},
{
"sucursalId": 4,
"nombre": "Santa Clara",
"barrioId": 1,
"empleados": [
],
"ventas": [
],
"barrio": null
},
{
"sucursalId": 5,
"nombre": "Santa Clara",
"barrioId": 2,
"empleados": [
],
"ventas": [
],
"barrio": null
}
]
What I want to achieve, is that in each Branch, with the neighborhood ID that I give him his neighborhood object, where Barrio = null does not say.
Then I implemented this:
public IEnumerable<Sucursales> Get()
{
using (var _context = new hn_asis_testContext())
{
var lista = new List<Sucursales>();
var lista2 = new List<Barrios>();
lista = _context.Sucursales.ToList();
lista2 = _context.Barrios.ToList();
foreach (var item in lista)
{
item.Barrio = lista2.FirstOrDefault(t => t.BarrioId == item.BarrioId);
}
return lista.ToList();
}
}
Which, does not return me Json set, but ONE only with the goal I wanted to reach.
Asi:
[
{
"sucursalId": 2,
"nombre": "Santa Clara",
"barrioId": 1,
"empleados": [
],
"ventas": [
],
"barrio": {
"barrioId": 1,
"nombre": "Santa Clara",
"clientes": [
],
"empleados": [
],
"sucursales": [
]
}
}
]