I have a problem. I have 2 tables which look like this:
Table1: Country
Name: Germany
ID: 1
Name: France
ID: 2
Table2: Cities
Name: Frankfurt
ID: 1
Name: Paris
ID: 2
I want to write a select statement where it compare the id’s and sorts the cities with the correct countries with the same id. The output should be in a json format.
My code look like this so far:
public class StadtHelper
{
public class STADT
{
public string StadtName { get; set; }
public string RegionID { get; set; }
}
internal static List<STADT> Stadt()
{
List<STADT> stadtObject = new List<STADT>();
using (SqlConnection con = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
using (SqlCommand cmd = new SqlCommand(@"SELECT NAME, REGION_ID FROM STADT",con))
{
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr["NAME"] != DBNull.Value && rdr["REGION_ID"] != DBNull.Value)
{
stadtObject.Add(new STADT()
{
StadtName = rdr["NAME"].ToString(),
RegionID = rdr["REGION_ID"].ToString()
});
}
}
}
}
return stadtObject;
}
}
Thanks in advance
i edited my code:
public class StadtHelper
{
public class STADT
{
public string StadtName { get; set; }
public string RegionName { get; set; }
}
internal static List<STADT> Stadt()
{
List<STADT> stadtObject = new List<STADT>();
using (SqlConnection con = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
using (SqlCommand cmd = new SqlCommand(@"SELECT REGION.NAME, STADT.NAME FROM REGION, STADT WHERE REGION.ID = STADT.REGION_ID ORDER BY REGION.NAME" , con))
{
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr["REGION.NAME"] != DBNull.Value && rdr["STADT.NAME"] != DBNull.Value)
{
stadtObject.Add(new STADT()
{
RegionName = rdr["REGION.NAME"].ToString(),
StadtName = rdr["STADT"].ToString()
});
}
}
}
}
return stadtObject;
}
}
there is still a bug, my web service gives me an exeption:
System.IndexOutOfRangeException: REGION.NAME
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at System.Data.SqlClient.SqlDataReader.get_Item(String name)
at StadtHelper.Stadt() in C:\Users\Yeah\Documents\Visual Studio 2010\Projects\WebService1\WebService1\StadtHelper.cs:line 31
at WebService1.Service1.Stadt() in C:\Users\Yeah\Documents\Visual Studio 2010\Projects\WebService1\WebService1\Service1.asmx.cs:line 77
Given your tables, the TSQL would look like,