当我运行我的代码时,它告诉我 adr 的对象为空,这是真的,但是为什么当它在相同方法的副本中工作时它不能工作,除了插入而不是选择。
代码如下所示:
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;
}
}
调用如下所示:
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
}