Error when obtaining value of a property through reflection

Asked

Viewed 139 times

0

I’m having trouble with the following line of code:

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

Every time he gets on this line he throws an exception

Object does not match the destination 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;
    }
}
  • See if it helps: http://answall.com/questions/44846/obten-valores-de-propriedades-de-class

  • 1

    It won’t be because I’m wearing .GetValue(this, null)? The this shouldn’t be entity?

1 answer

0


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

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

This way, and add if(Entity == null) before creating the key variable as 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 in fiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.