我正在尝试执行删除,但我需要确保在尝试删除之前存在一个值。该值是从数据库中提取的。我需要检查 dbnull。如果不是,则删除可以继续。我尝试了以下但它不起作用:
if (!DBNull.Value.Equals(x.ColourImage))
{
File.Delete(HttpContext.Current.Server.MapPath(x.ColourImage));
}
当我尝试时出现以下异常:
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.
****编辑**** 我已经看到了建议的问题,但这些解决方案似乎都没有帮助。无论我尝试什么,我都会遇到同样的异常。
**** 我的完整代码使用了建议的答案,但我仍然得到相同的异常 ****
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;
}
* 更新 *
我尝试了以下方法,但出现异常: public bool DeleteProductColour(int colid, int prd) { bool prodColourDeleted = false; 尝试 { 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;
}
我得到的异常是
'product.ColourImage' threw an exception of type 'System.Data.StrongTypingException'
最佳答案
在强类型的DataSet
中会出现这种问题。
可能在填充您的 Dataset
之前,获取相应的 DataColumn
并将 DataColumn.AllowDBNull
设置为 true。
https://msdn.microsoft.com/en-us/library/system.data.datacolumn.allowdbnull(v=vs.110).aspx
关于c# - 检查数据库值是否因数据库中的空值而无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50654518/