0
I am using ASP.Net to create a REST API
I’m trying to create a method that returns a list of groups structured this way:
{
"IdGroup": "1",
"NameGroup": "Group1",
"Installations": [
{
"IdInstallation": "1",
"NameInstallation": "Installation 1"
},
{
"IdInstallation": "2",
"NameInstallation": "Installation 2"
},
{
"IdInstallation": "3",
"NameInstallation": "Installation 3"
},
{
"IdInstallation": "4",
"NameInstallation": "Installation 4"
}
]
}
But my method is only returning the last installation of the group (installation 4, in this case).
My method:
[HttpPost]
[Route ("groups")]
public HttpResponseMessage GetGroups()
{
try
{
List<Groups> listGroups = new List<Groups>();
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "select Groups.IdGroup, Groups.NameGroup, AttributeCloned.IdInstallation, AttributeCloned.NameInstallation " +
"from Groups " +
"join AttributeCloned " +
"on Groups.IdGroup = AttributeCloned.IdGroup "+
"where Groups.IdGroup = 1 "+
"order by IdInstallation asc";
SqlDataReader reader = command.ExecuteReader();
Groups group = new Groups();
Installations inst = new Installations();
while (reader.Read())
{
group.IdGroup = reader["IdGroup"] == DBNull.Value ? 0 : Convert.ToInt32(reader["IdGroup"]);
group.NameGroup = reader["NameGroup"] == DBNull.Value ? string.Empty : reader["NameGroup"].ToString();
inst.IdInstallation = reader["IdInstallation"] == DBNull.Value ? 0 : Convert.ToInt32(reader["IdInstallation"]);
inst.NameInstallation = reader["NameInstallation"] == DBNull.Value ? string.Empty : reader["NameInstallation"].ToString();
}
group.installations.Add(inst);
listGroups.Add(group);
}
}
return Request.CreateResponse(HttpStatusCode.OK, listGroups.ToArray());
}
catch(Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
What I am missing so that not be returned all the facilities of the respective group?
Unrelated to the question, but the method should not be used
GET
, in place ofPOST
?– tvdias
I added the answer with what I believe is the problem, but I was curious to know why you do not seek to use one
ORM
.– tvdias
Add your base’s DDL and DML to the question, so you can reproduce the problem.
– tvdias