I am trying to perform a delete but I need to make sure that a value is present before trying to delete. The value is pulled from the database. I need to check for dbnull. If it's not, then the delete can go ahead. I have tried the following but it does not work:
if (!DBNull.Value.Equals(x.ColourImage))
{
File.Delete(HttpContext.Current.Server.MapPath(x.ColourImage));
}
When I try I get the following exception:
Inner Exception Type: System.InvalidCastException
Unable to cast object of type 'System.DBNull' to type 'System.String'.
Inner Source: App_Code.bvtnyzaw
Inner Stack Trace:
at Products.GetAllProdColoursRow.get_ColourImage() in c:\Users\micha\AppData\Local\Temp\Temporary ASP.NET Files\vs\d9cd3740\a9faac06\App_Code.bvtnyzaw.2.cs:line 2245Exception Type: System.Data.StrongTypingException
Exception: The value for column 'ColourImage' in table 'GetAllProdColours' is DBNull.
****EDIT**** I have already seen the suggested question but none of those solutions seemed to help. No matter what I try I get the same exception.
**** My complete code using the suggested answer but still I get the same exception ****
public bool DeleteProductColour(int colid, int prd)
{
bool prodColourDeleted = false;
try
{
var x = pcAdp.GetAllProdColours(prd).AsEnumerable().Where(y => y.ColourId == colid).First();
if (x != null && !string.IsNullOrEmpty(x.ColourImage))
{
File.Delete(HttpContext.Current.Server.MapPath(x.ColourImage));
}
pcAdp.DeleteProductColour(colid);
prodColourDeleted = true;
}
catch(Exception er)
{
ExceptionUtility.LogException(er, "Delete product colour - ProductsBLL");
}
return prodColourDeleted;
}
* UPDATE *
I have tried the following but I get an exception: public bool DeleteProductColour(int colid, int prd) { bool prodColourDeleted = false; try { var x = pcAdp.GetAllProdColours(prd).ToList();
if (x.Any())
{
var colour = x.Where(y => y.ColourId == colid).FirstOrDefault();
if (colour != null && !string.IsNullOrEmpty(colour.ColourImage))
{
File.Delete(HttpContext.Current.Server.MapPath(colour.ColourImage));
}
}
pcAdp.DeleteProductColour(colid);
prodColourDeleted = true;
}
catch (Exception er)
{
ExceptionUtility.LogException(er, "Delete product colour - ProductsBLL");
}
return prodColourDeleted;
}
The exception I get is
'product.ColourImage' threw an exception of type 'System.Data.StrongTypingException'