简体   繁体   English

System.InvalidCastException:“无法将对象从 DBNull 转换为其他类型。” 从数据库转换为 Object

[英]System.InvalidCastException: 'Object cannot be cast from DBNull to other types.' in Conversion from Database to Object

I have a problem when i try to set a DateTime from my datebase.当我尝试从我的数据库设置日期时间时遇到问题。 i am having a DBnull tjek.我有一个 DBnull tjek。 and i have made my Datetime nullabel.我已经将我的日期时间设为空标签。 cant figurer out why.不知道为什么。

  public static List<ExportElements> GetExportElementsForCase(int caseNumber)
    {
        using (var dataAccess = new DbConnection<SqlConnection>())
        {
            DataTable dbExportElements = new DataTable();
            dataAccess.ExecuteCommand<DataTable>(command =>
            {
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "GetElementsForEksport";

                var caseNr = command.CreateParameter();
                caseNr.ParameterName = "@caseNumberTolookUp";
                caseNr.Value = caseNumber;
                command.Parameters.Add(caseNr);

                var reader = command.ExecuteReader();
                //Create a new DataTable.
                DataTable resultToReturn = new DataTable("exportElements");

                //Load DataReader into the DataTable.
                resultToReturn.Load(reader);
                dbExportElements = resultToReturn;
                return resultToReturn;
            });

            List<ExportElements> exportMarterials = new List<ExportElements>();
            exportMarterials = (from DataRow dr in dbExportElements.Rows
                                select new ExportElements()
                                {
                                    CaseNumber = Convert.ToInt32(dr["CaseNumber"]),
                                    SubCaseNumber = Convert.ToInt32(dr["SubCaseNumber"]),
                                    ElementNumber = dr["ElementNumber"].ToString(),
                                    Side3To4 = Convert.ToDouble(dr["Side3To4"]),
                                    Side2To5 = Convert.ToDouble(dr["Side2To5"]),
                                    Side1To6 = Convert.ToDouble(dr["Side1To6"]),
                                    Weight = Convert.ToDouble(dr["Weight"]),
                                    Volume = Convert.ToDouble(dr["Volume"]),
                                    ProductNumber = Convert.ToInt32(dr["ProductNumber"]),
                                    DepartmentNumber = Convert.ToInt32(dr["DepartmentNumber"]),
                                    TurnElement = Convert.ToBoolean(dr["TurnElement"]),
                                    ErektionSeqence = Convert.ToInt32(dr["ErektionSeqence"]),
                                    ID = Convert.ToInt32(dr["ID"]),
                                    ReleasedDate = dr["ReleasedDate"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(dr["ReleasedDate"]),
                                    ElementBasicPart = dr["ElementBasicPart"].ToString(),
                                    RevisionsLetter = dr["RevisionsLetter"].ToString(),
                                    ElementStatus = Convert.ToInt32(dr["ElementStatus"]),
                                    RevisionsText = dr["RevisionsText"].ToString(),
                                    EnvironmentalClass = Convert.ToInt32(dr["EnvironmentalClass"]),
                                    LedgeHeight1 = Convert.ToDouble(dr["LedgeHeight1"]),
                                    LedgeHeight2 = Convert.ToDouble(dr["LedgeHeight2"]),
                                    IsClosed = Convert.ToBoolean(dr["IsClosed"]),
                                    RevitTemplate = dr["revitTemplate"].ToString(),
                                }).ToList();

            return exportMarterials;
        }
    }

It is the releaseDate that fails.失败的是 releaseDate。

The Model i am converting to from the DataRow.我正在从 DataRow 转换为 Model。

public class ExportElements
{
    public int CaseNumber { get; set; }
    public int SubCaseNumber { get; set; }
    public string ElementNumber { get; set; }
    public double Side3To4 { get; set; }
    public double Side2To5 { get; set; }
    public double Side1To6 { get; set; }
    public double Weight { get; set; }
    public double Volume { get; set; }
    public int ProductNumber { get; set; }
    public int DepartmentNumber { get; set; }
    public bool TurnElement { get; set; }
    public int ErektionSeqence { get; set; }
    public int ID { get; set; }
    public DateTime? ReleasedDate { get; set; }
    public string ElementBasicPart { get; set; }
    public string RevisionsLetter { get; set; }
    public int ElementStatus { get; set; }
    public string RevisionsText { get; set; }
    public int EnvironmentalClass { get; set; }
    public double LedgeHeight1 { get; set; }
    public double LedgeHeight2 { get; set; }
    public bool IsClosed { get; set; }
    public string RevitTemplate { get; set; }
}

It works in other conversion with the same Datarow to DateTime conversion它适用于具有相同数据行到 DateTime 转换的其他转换

I found the problem.我发现了问题。 it was not the DateTime?这不是日期时间吗? but the "ErektionSeqence" that was also DBNull witch i forgot to make a check for.但是我忘记检查也是 DBNull 女巫的“ErektionSeqence”。

Instead of using all those Convert calls when you're not actually converting anything, I suggest that you use the Field method from LINQ to DataSet.我建议您使用从 LINQ 到 DataSet 的Field方法,而不是在您实际上没有转换任何内容时使用所有这些Convert调用。 It can handle nulls.它可以处理空值。 Eg例如

NonNullableReferenceTypeProperty = row.Field<string>("Column1"),
NullableReferenceTypeProperty = row.Field<string>("Column2"),
NonNullableValueTypeProperty = row.Field<DateTime>("Column3"),
NullableValueTypeProperty = row.Field<DateTime?>("Column4"),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 system.invalidcastexception 'object cannot be cast from dbnull to other types.' - system.invalidcastexception 'object cannot be cast from dbnull to other types.' System.InvalidCastException:无法将对象从DBNull强制转换为其他类型 - System.InvalidCastException: Object cannot be cast from DBNull to other types MySqlConnection.Open() System.InvalidCastException: 对象无法从 DBNull 转换为其他类型 - MySqlConnection.Open() System.InvalidCastException: Object cannot be cast from DBNull to other types 当Checkbox值为null时。 程序抛出此错误“对象不能从DBNull强制转换为其他类型。” - When Checkbox value is null. Program throws this error“ Object cannot be cast from DBNull to other types.” 无法将对象从DBNull强制转换为其他类型。 读取器读取空值时出错 - Object cannot be cast from DBNull to other types. Error when a null value is read by the Reader 错误。 '对象不能从 DBNull 转换为其他类型。' C# 与方法 sum() - Error! 'Object cannot be cast from DBNull to other types.' C# with method sum() 无法将对象从DBNull强制转换为其他类型 - Object cannot be cast from DBNull to other types 无法将对象从DBNull强制转换为其他类型 - Object cannot be cast from DBNull to other types “无法将对象从DBNull强制转换为其他类型” - “Object cannot be cast from DBNull to other types” 无法将对象从DBNull强制转换为其他类型 - The Object cannot be cast from DBNull to other types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM