2

I need to reflect a property for lambda for my Repository, here's the code:

public abstract class RestController<T> : Controller where T : class
{
    private readonly IRepository _db;
    private readonly string _identityProp;

    protected RestController(IRepository db, string identityProp)
    {
        _db=db;
        _identityProp = identityProp;
    }

    protected virtual void Delete(T item)
    {
        var value = item.GetType().GetProperty(_identityProp).GetValue(item, null);
        var items = _db.All<T>()
            .Where(i=>i.GetType().GetProperty(_identityProp)==val)
            .ToList();
        items.ForEach(x=>_db.Delete(x));
        _db.CommitChanges();
        return Json("success");
    }
}

but the result of lambda is an empty list... Help please, what I'm doing wrong?

CodeAddicted
  • 979
  • 2
  • 10
  • 13

1 Answers1

2

You are missing a .GetValue(i, null) in your LINQ query. Currently, you are comparing the value of the property (value) with the PropertyInfo describing the property.

Correct code:

var items = _db.All<T>()
               .Where(i => i.GetType().GetProperty(_identityProp)
                                      .GetValue(i, null) == val)
               .ToList();

Or, a little bit more performance orientated:

var propertyInfo = item.GetType().GetProperty(_identityProp);
var value = propertyInfo.GetValue(item, null);
var items = _db.All<T>()
               .Where(i => propertyInfo.GetValue(i, null) == val)
               .ToList();
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443