如何使用refelection处理null

时间:2016-10-12 07:12:41

标签: c# reflection

我正在尝试设置对象的值。我因Object of type 'System.DBNull' cannot be converted to type 'System.Nullable1[System.DateTime]' a而收到错误。如何使用反射处理null。

我尝试像在链接中描述的那样解决,但它不会帮助我。

我得到了这个 How to set property value using reflection in C#

    protected TEntity ToFirst(IDbCommand command)
    {
        using (var record = command.ExecuteReader())
        {
            var items = new TEntity();
            while (record.Read())
            {
                items = Map<TEntity>(record);
            }
            return items;
        }
    }

    protected TEntity Map<TEntity>(IDataRecord record)
    {
        var objT = Activator.CreateInstance<TEntity>();
        foreach (var prop in typeof(TEntity).GetProperties())
        {
            var attributes = prop.GetCustomAttributes(false);
            var columnMapping = attributes.FirstOrDefault(a => a.GetType() == typeof(DbColumnAttribute));
            if (columnMapping != null)
            {
                var map = columnMapping as DbColumnAttribute;
                if (map != null && (record.HasColumn(map.Name) && record.IsDBNull(record.GetOrdinal(map.Name))))
                    prop.SetValue(objT, record[prop.Name]);
            }
            else
            {
                if (record.HasColumn(prop.Name) && record.IsDBNull(record.GetOrdinal(prop.Name)))
                    prop.SetValue(objT, record[prop.Name]);
            }
        }
        return objT;
    }

0 个答案:

没有答案