我正在尝试从查询表达式结果动态地将行添加到数据表中。但是,我收到以下异常:“无法将 DBNull.Value 转换为类型 'System.Int16'。请使用可为空的类型。”
这是我的代码:
foreach (var linqItem in linqResult)
resultDT.Rows.Add(linqItem.GetType().GetProperties().Select(p => p.GetValue(linqItem, null)).ToArray());
请帮我弄清楚这个问题。
附加代码:
var linqResult = from misDTRow in misUserDetailsDT.AsEnumerable()
join deptDTRow in departmentInfoDT.AsEnumerable()
on misDTRow.Field<Int16>("DepartmentID") equals deptDTRow.Field<Int32>("DeptID")
select
new
{
Username = misDTRow["LoginName"],
EmployeeID = misDTRow["EmployeeID"],
EmployeeName = misDTRow["EmployeeName"],
FoundIn = misDTRow["FoundIn"],
StatusInMIS = (bool)misDTRow["IsActive"] == true ? "Inactive" : "Active",
Department = deptDTRow["DeptName"]
};
数据表创建:
DataTable resultDT = new DataTable();
PropertyInfo[] propInfo = linqResult.First().GetType().GetProperties();
foreach (PropertyInfo property in propInfo)
resultDT.Columns.Add(property.Name, property.PropertyType);
我正在从查询结果动态创建 DataTable。