mercredi 12 octobre 2016

How to handle null using refelection

I am trying to set the value of object. I get the error because of null a. How to handle null?

I tried to solve like in described at the link but it won't help me.

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;
    }





Aucun commentaire:

Enregistrer un commentaire