不会接受C#中的null对象

时间:2013-03-06 13:26:34

标签: c# object nullable 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;
    }
}

电话看起来像这样:

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
}

3 个答案:

答案 0 :(得分:8)

嗯,是的,看:

if (city == null)
{
    // If we've got in here, we know that city is a null reference, but...
    city = city.create(...);
}

您正在调用绝对 null的引用上的方法。这保证会抛出NullReferenceException

您几乎肯定希望将create方法设置为静态(并将其重命名为符合正常的.NET命名约定),并将其称为

city = City.Create(...);

您还需要从方法调用中删除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;
    }
}

请注意我是如何更改代码以使用参数化SQL的。实际上,您确实不应该将值直接放入SQL语句中 - 它会将您的系统打开到SQL injection attacks并使各种转换变得混乱。

此外,我建议为每个数据库操作创建一个新的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)

存储库将知道相关的连接字符串,并负责所有数据库操作。 City类型对数据库一无所知。

答案 1 :(得分:0)

您正在尝试在尚未初始化的对象类上调用方法/为null。

您需要将City.create设为静态成员。

public static 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;
    }
}

并使用它:

if(city==null) 
{
    City city = City.create(... );
}

答案 2 :(得分:0)

更好的方法:

 static public 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))
     {
         object ID = command.ExecuteScalar();

         City city = new City();
         city.id = Convert.ToInt32(ID);
         city.postnr = postnr;
         city.navn = navn;
         return city;
     }

     return null;
 }

Create方法必须是静态的,并且不需要在参数中包含city。 称之为:

 if (city == null)
 {
      city = City.Create(.....);
 }