简体   繁体   中英

Create dynamic Expression<Func<T, bool>>

I don't know if this is possible or not but I'm trying to refactor my code logic by doing the following;

I have a method called: ApproveProcess<T1, T2>(T1 classObject, T2 classSecondObject) where T : class

T is the generic object that I'm passing to the ApproveProcess method. I have then the following method:

public IQueryable<T> GetById(Expression<Func<T, bool>> condition, Func<IQueryable<T>)
{
           IQueryable<T> query = _entities.Where(condition);
           return query;
}

I am trying to do the following:

Expression<Func<T1, bool>> expr2 = z => z.GetType().GetProperty("StringNumber").ToString() == "IB56";
BaseRepository<T1> iBase = new BaseRepository<T>(_databaseContext);
var tester1 = iBase. GetById(expr2, null).ToList();

I am trying to dynamically create the expression function based on the generic T object to then returns results.

I am not getting anyway. If I change

`Expression<Func<T1, bool>> expr2' 

to

Expression<Func<actualObject, bool>> expr2 

I then get the following error

Error CS1503 Argument 1: cannot convert from 'System.Linq.Expressions.Expression>' to 'System.Linq.Expressions.Expression>'

Is anyone able to tell me if what I am trying to do is actually possible? Any pointers to point me in the right direction would be grateful / Help?

Code Sample below;

_uowAdmin.AdminRepository.ApproveProcess<MeetingOne, MeetingRoomOne, MeetingRoomTwo>(new MeetingRoomOne(), new MeetingRoomTwo());
_uowAdmin.AdminRepository.ApproveProcess<DiningOne, DiningRoomOne, DiningRoomTwo>(new DiningRoomOne(), new DiningRoomTwo());


public void ApproveProcess<T, T1, T2>(T1 classObject, T2 classSecondObject) where T : class
{

    BaseRepository<T> iBase = new BaseRepository<T>(_databaseContext);
    Expression<Func<T, bool>> expr2 = z => z.GetType().GetProperty("StringNumber").ToString() == "IB56";
    var tester1 = iBase.GetById(expr2, null).ToList();
}

public class BaseRepository<T> where T : class
{

    public IQueryable<T> GetById(Expression<Func<T, bool>> condition, Func<IQueryable<T>)
    {
           IQueryable<T> query = _entities.Where(condition);
           return query;
    }
}

Try this:

var parameter = Expression.Parameter(typeof(T), "z");
var expr2 = Expression.Lambda<Func<T, bool>>(
    Expression.Equal(
        Expression.Property(parameter, "StringNumber"),
        Expression.Constant("IB56")),
    parameter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM