Additional information: 对象不能从 DBNull 转换为其他类型。

空白里的亮点 2018-01-03 01:56:59

public static T DataRowToT<T>(DataRow source) where T : class,new()
{
T item = null;
if (source == null)
{
return item;
}
item = new T();
Type targettype = typeof(T);
Type ptype = null;
Object value = null;
foreach (PropertyInfo pi in targettype.GetProperties())
{
if (pi.CanWrite && source.Table.Columns.Contains(pi.Name))
{
ptype = Type.GetType(pi.PropertyType.FullName);
if (!(pi.PropertyType.FullName == "System.Byte[]" && source[pi.Name] == System.DBNull.Value))
{
value = Convert.ChangeType(source[pi.Name], ptype);
pi.SetValue(item, value, null);

}

}
}
return item;
}
...全文
184 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
不管类型是 string 还是 byte[ ],都是一样,要对于可能为空的返回数据首先判断 DBNull。 另外,尽量不要写反射代码。
  • 打赏
  • 举报
回复
var cmd = dbconn.CreateCommand();
cmd.CommandText = $"select Id, UserName,UserCode,UserNumber from User";
using (var reader = cmd.ExecuteReader())
{
    var lst = (from IDataRecord x in reader
                select new MyDataType
                {
                    Id = (string)x[0],
                    Name = (string)x[1],
                    ShenFenZheng = x[2] == DBNull.Value ? null : (string)x[2],
                    Number = x[3] == DBNull.Value ? 0 : (int)x[3]
                }).ToList();
    proc(lst);
}
  • 打赏
  • 举报
回复
从 ADO.NET 查询出来的 DataReader[....] 是弱类型的(object 的),它的值可能是 DBNull。所以对于这类数据就不能随便简单地转换。例如:
var cmd = dbconn.CreateCommand();
cmd.CommandText = $"select Id, UserName,UserCode from UscUser";
using (var reader = cmd.ExecuteReader())
{
    var lst = (from IDataRecord x in reader
                select new MyDataType
                {
                    Id = (string)x[0],
                    Name = (string)x[1],
                    ShenFenZheng = (string)x[2],
                    Number = x[3] == DBNull.Value ? 0 : (int)x[3]
                }).ToList();
    proc(lst);
}
这里,对于不可能为空的字段就不处理了,但是对于可能为空的字段(Number)就需要判断是否为空,为空就应该进行特殊处理。
  • 打赏
  • 举报
回复
判断条件里&&改为||

110,549

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧