-1

I am trying to insert NULL value in Sql Server if I have null value in corresponding C# String object like below :

String Residence = xmlDoc.Descendants("Appointment").Single().Element("StateOfResidence") == null ? null : xmlDoc.Descendants("Appointment").Elements("StateOfResidence").Single().Value;

I am using Entity framework for Database access. So if Residence is null, 'NULL' gets inserted into Database instead of NULL. How can insert NULL for null ?

Anand
  • 165
  • 3
  • 15

2 Answers2

1

A databases null value is of a different type to the regular null values that you use in C#. So to insert a null value into a database you must use the below code type, instead of null or "NULL"

DBNull.Value
Amicable
  • 3,115
  • 3
  • 49
  • 77
Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70
1

Entity Framework should handle this for you, so the issue you have is that

xmlDoc.Descendants("Appointment").Single().Element("StateOfResidence")

actually has the string value "NULL"

you could change your logic to say that

String Residence = xmlDoc.Descendants("Appointment").Single().Element("StateOfResidence");
if(Residence == "NULL")
{
    Residence = null;
}

but that's a bit hacky really - I'd personally be looking at why the xml you have actually has the string value "NULL" in what presumably should be empty nodes if the xml is under your control.

ajg
  • 1,743
  • 12
  • 14