简体   繁体   中英

Error when trying to retrieve from database

I have generated three classes from XSD schema:

public partial class PathDetailsMessage {
    private MessageHeader messageHeaderField;

    public MessageHeader MessageHeader {
        get {
            return this.messageHeaderField;
        }
        set {
            this.messageHeaderField = value;
        }
    }
}


public partial class MessageHeader {
    private Recipient recipientField;

    public Recipient Recipient {
        get {
            return this.recipientField;
        }
        set {
            this.recipientField = value;
        }
    }
}


public partial class Recipient {
    private string valueField;

    public string Value {
        get {
            return this.valueField;
        }
        set {
            this.valueField = value;
        }
    }
}

When I try to put the value of id (which is a char in database) to medusa.MessageHeader.Recipient.Value, I get an error (see below):

if (dr.HasRows)
{
  dr.Read();
  medusa.MessageHeader.Recipient.Value = Convert.ToString(dr["id"]);
  dr.Close();
}

I get the following error:

 System.NullReferenceException: 'Object reference not set to an instance of an object.' PathDetailsMessage.MessageHeader.get returned null.

I use the following SQL string:

string sqlString = "SELECT id FROM view_otf WHERE id LIKE '%079%'";

id column is CHAR in database.

I can't figure out a solution for this issue.

Can you help me?

Thank you.

LE : Those 3 classes are in the same.cs file.

LE2 : medusa is an object initialized from the PathDetailsMessage.cs file, class that was created from XSD schema

PathDetailsMessage medusa = new PathDetailsMessage();

We are missing the medusa initialization code, but you should do something like this:

medusa.MessageHeader = new MessageHeader {
    Recipient = new Recipient()
};
medusa.MessageHeader.Recipient.Value = Convert.ToString(dr["id"]);

That is because the initialization of a class like PathDetailsMessage will set no value to the MessageHeader property which will be null. The same applies to the Recipient property. So with the above initialization, you'll have some object to store the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM