0

To clarify: If a node doesn't exist how do I get the null value inserted into the database.

This is one of 4 places each value/name occurs so I will describe the life of one item to be as clear as possible.

First in the LINQ section setting the variable:

    lastDateToOrder = (string) x.Descendants("lastDateToOrder").FirstOrDefault
    //This will either populate a date or null

Second is the SQL statement:

    string qry = @"Insert into TABLE
                   (lastDateToOrder)
                  values(@lastDateToOrder)";

Finally, setting the parameter:

    qryInsert.Parameters
    .Add("@lastDateToOrder", SqlDbType.DateTime).Value = entry.lastDateToOrder;

The finally section is the part causing problems because I am getting an error saying that @lastDateToOrder is not getting defined and I can see this is the case only when the value is null.

I can't figure out what is wrong and why when entry.lastDateToOrder is carrying a null value it doesn't get set as null.

jww
  • 97,681
  • 90
  • 411
  • 885
KeithL
  • 5,348
  • 3
  • 19
  • 25
  • You need to check for `null` values in your code before you use them. And of course you need to validate your xml if you have missing nodes which are `required` by design. – Yahya May 12 '14 at 14:56
  • The XML is valid and unalterable, however, it contains many optional nodes. The SQL Server table that I am inserting into does allow nulls for these optional columns. – KeithL May 12 '14 at 15:04
  • You can start with nullable variables for each value which needs to go in the database. Then read the values from XML, if they are null, set those variables as null. Then you just have to do your database operation. – Yahya May 12 '14 at 15:08

1 Answers1

0

Found this answer by digging into another question.

Assign null to a SqlParameter

qryInsert.Parameters
.Add("@lastDateToOrder", SqlDbType.DateTime).Value = (object) entry.lastDateToOrder ?? DBNull.Value
Community
  • 1
  • 1
KeithL
  • 5,348
  • 3
  • 19
  • 25