How would I get data from a SQL Server table where there is null and convert it to a string in Web API ?`
I get this error:
Unable to cast object of type 'System.DBNull' to type 'System.String'
My code:
SqlCommand AGetCommand = new()
{
Connection = DataSource,
CommandType = CommandType.StoredProcedure,
CommandText = "GetCustomers"
};
SqlDataReader AGetCommandDataReader;
AGetCommandDataReader = AGetCommand.ExecuteReader();
List<Customer> ExampleCustomers = new();
if (AGetCommandDataReader.HasRows)
{
while (AGetCommandDataReader.Read())
{
Customer ExampleCustomer = new()
{
CustomerID = (string)AGetCommandDataReader["CustomerID"],
CompanyName = (string)AGetCommandDataReader["CompanyName"],
ContactName = (string)AGetCommandDataReader["ContactName"],
ContactTitle = (string)AGetCommandDataReader["ContactTitle"],
Address = (string)AGetCommandDataReader["Address"],
City = (string)AGetCommandDataReader["City"],
Region = (string)AGetCommandDataReader["Region"],
PostalCode = (string)AGetCommandDataReader["PostalCode"],
Country = (string)AGetCommandDataReader["Country"],
Phone = (string)AGetCommandDataReader["Phone"],
Fax = (string)AGetCommandDataReader["Fax"]
};
ExampleCustomers.Add(ExampleCustomer);
}
}
AGetCommandDataReader.Close();
DataSource.Close();
return ExampleCustomers;