Error getting value of property through reflection

0

I'm having problems in the following line of code:

var key = entity.GetType().GetProperties().FirstOrDefault(p => p.Name.ToLower().Contains("id")).GetValue(this, null);

Whenever this line arrives it throws an exception

  

The object does not match the target type.

The whole method is this:

public void AddOrUpdate(TEntity entity)
{
    var key = entity.GetType().GetProperties().FirstOrDefault(p => p.Name.ToLower().Contains("id")).GetValue(this, null);

    if (entity == null)
        throw new ArgumentNullException("entity");

    if ((int)key == 0)
    {
        _entities.Set<TEntity>().Add(entity);
    }
    else
    {
        _entities.Entry(entity).State = EntityState.Modified;
    }
}
    
asked by anonymous 19.01.2017 / 14:15

1 answer

0

The correct way to use GetValue is to pass the Object, passing this you are passing the class that this function is in this context.

var key = entity.GetType().GetProperties().FirstOrDefault(p => p.Name.ToLower().Contains("id")).GetValue(entity);

In this way, add the if (entity == null) before creating the key variable because a null pointer error may occur.

 public void AddOrUpdate<TEntity>(TEntity entity)
        {               

        if (entity == null)
                throw new ArgumentNullException("entity");

        var key = entity.GetType().GetProperties().FirstOrDefault(p => p.Name.ToLower().Contains("id")).GetValue(entity);



         if ((int)key == 0)
            {
                _entities.Set<TEntity>().Add(entity);
            }
            else
            {
                _entities.Entry(entity).State = EntityState.Modified;
            }

        }

Example on fiddle

    
19.01.2017 / 14:36