Mic*_*ard 0 c# nullable object nullreferenceexception
当我运行我的代码时,它告诉我adr的对象是null,这是真的,但是当它在同一个方法的副本中工作时,为什么它不会工作,使用insert而不是select的例外.
代码如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这个电话看起来像这样:
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
}
Run Code Online (Sandbox Code Playgroud)
是的,看看:
if (city == null)
{
// If we've got in here, we know that city is a null reference, but...
city = city.create(...);
}
Run Code Online (Sandbox Code Playgroud)
您正在调用一个绝对为 null 的引用方法.这保证会抛出一个NullReferenceException.
您几乎肯定希望将您的create方法设置为静态(并将其重命名为符合正常的.NET命名约定),并将其命名为
city = City.Create(...);
Run Code Online (Sandbox Code Playgroud)
您还需要删除city从方法调用的参数,而是创建一个新的City对象里面的方法.例如:
public static City Create(string postnr, string navn, SqlConnection con)
{
DatabaseConnection.openConnection(con);
using (var command = new SqlCommand
("insert into [By] (Postnummer, Navn) values (@postnr, @navn); "+
"select @@identity as 'identity';", con))
{
command.Parameters.Add("@postnr", SqlDbType.NVarChar).Value = postnr;
command.Parameters.Add("@navn", SqlDbType.NVarChar).Value = navn;
object ID = command.ExecuteScalar();
City = new City();
city.id = Convert.ToInt32(ID);
city.postnr = postnr;
city.navn = navn;
return city;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意我是如何更改代码以使用参数化SQL的.实际上,您确实不应该将值直接放入SQL语句中 - 它会使您的系统开启SQL注入攻击并使各种转换变得混乱.
另外,我建议SqlConnection为每个数据库操作创建一个新的(并关闭它).
坦率地说doesExist,成为一个实例方法也有点奇怪......再次,它需要一个city参数.
我建议改变它的设计,以便你有一个CityRepository(或类似的东西)知道连接字符串,并暴露:
// I'd rename these parameters to be more meaningful, but as I can't work out what they're
// meant to mean now, it's hard to suggest alternatives.
public City Lookup(string postnr, string nav)
public City Create(string postnr, string nav)
Run Code Online (Sandbox Code Playgroud)
存储库将知道相关的连接字符串,并负责所有数据库操作.该City类型对数据库一无所知.