Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property Selector and Where<T> Query using Linq

Tags:

c#

lambda

linq

I'm trying to do that :

public class SomeEntityClass
{
    public Guid MyClassProperty {get;set;}
}

public class AnotherEntityClass
{
    public Guid AnotherProperty {get;set;}
}

public T GetByProperty<T>(Guid value, Expression<Func<T, object>> selector)
{
    return = Session.Query<T>().Where(x => selector == value).FirstOrDefault();
}

Should be called :

Repository.GetByProperty<SomeEntityClass>(Guid.NewGuid(), x => x.MyClassProperty );
Repository.GetByProperty<AnotherEntityClass>(Guid.NewGuid(), x => x.AnotherProperty);

but it doesn't work.

Any help ?

Thanks.

like image 937
Yoann. B Avatar asked Dec 28 '22 11:12

Yoann. B


1 Answers

Try to use something like that:

public T GetByProperty<T, TValue>(TValue value, Expression<Func<T, TValue>> selector) {
    var predicate = Expression.Lambda<Func<T, bool>>(
        Expression.Equal(selector.Body, Expression.Constant(value)), 
        selector.Parameters
    );

    return Session.Query<T>().Where(predicate).FirstOrDefault();
}
like image 193
hazzik Avatar answered Jan 04 '23 22:01

hazzik