When I run my code it tells me that the object of adr is null, and thats true, but why wont it work when it works in a duplicate of the same method, with the exeption of insert instead of select.
the code looks like this:
public City doesExist(string postnr, string navn, City city, SqlConnection con)
{
DatabaseConnection.openConnection(con);
using (var command = new SqlCommand("select Id from [By] where Postnummer='" + postnr + "' and Navn='" + navn + "'", con))
{
command.Connection = con;
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
city.id = reader.GetInt32(0);
city.postnr = postnr;
city.navn = navn;
reader.Close();
return city;
}
reader.Close();
return null;
}
}
public City create(string postnr, string navn, City city, SqlConnection con)
{
DatabaseConnection.openConnection(con);
using (var command = new SqlCommand("insert into [By] (Postnummer, Navn) values ('" + postnr + "', '" + navn + "'); select @@identity as 'identity';", con))
{
object ID = command.ExecuteScalar();
city.id = Convert.ToInt32(ID);
city.postnr = postnr;
city.navn = navn;
return city;
}
}
the call looks like this:
City city = new City();
city = city.doesExist(zip, by, city, connection); // this works fine
if (city == null)
{
// I know that city is null
// tried inserting City city = new City(); same error
city = city.create(zip, by, city, connection); // this is where the null error occours
}
createmethod an instance method of theCityclass? Of course it will throw an exception. After all,cityis null, isn't it?static?doesExistmethod also takes an inputcityparameter which is unused, and should be removed. Actually, both of these methods look like repository methods, i.e. they should not be instance methods of a city class (because they don't belong to a single city instance).