Home > Back-end >  How to generic Expression with "where" clause?
How to generic Expression with "where" clause?

Time:12-07

I want a entity that filters the list entity within the entity.

I have entities with common structure like below

public class FoodMenuT
{
   public int Id {get;set;}
   
   public int LanguageId {get;set;}
   
   public string Name {get;set;}
}
public class FoodMenu
{
   public int Id {get;set;}
   
   public IEnumerable<FoodMenuT> FoodMenuTList {get;set;}
}

public static Expression<Func<FoodMenu, IEnumerable<FoodMenuT>>> LanguageFilter()
{

    return e => e.FoodMenuT.Where(x => x.LanguageId == 1);

}

What I want to do is to do this in a generic way.

public static Expression<Func<T, IEnumerable<TT>>> LanguageFilter<T, TT>()
{
    
}

Thank you in advance for your helps.

    public static Expression<Func<T, IEnumerable<TT>>> LanguageFilter<T, TT>()
        {
            var headerInfo = ServiceTool.ServiceProvider.GetService<IHeaderInfo>();


            var entity = typeof(T);

            var ttEntity = typeof(TT);

            var propertyInfo = entity.GetProperty(ttEntity.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);

            var arg = Expression.Parameter(entity, "e");

            var property = Expression.Property(arg, propertyInfo!.Name);

            //e=>e.FoodMenuT
            var selector = Expression.Lambda(property, new ParameterExpression[] { arg });

            var propertyInfo2 = ttEntity.GetProperty("LanguageId", BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);


            var arg2 = Expression.Parameter(ttEntity, "x");

            var property2 = Expression.Property(arg2, propertyInfo2!.Name);

            var languageId = Expression.Constant(headerInfo!.LanguageId);

            var equalLanguage = Expression.Equal(property2, languageId);

            //x=>x.LanguageId==1
            var selector2 = Expression.Lambda<Func<TT, bool>>(equalLanguage, arg2);

I couldn't combine "selector" and "selector2" with "where".

        var lambda = Expression.Lambda<Func<T, IEnumerable<TT>>>(null, arg);

        return lambda;
    }

CodePudding user response:

I solved the problem with my own means

public interface ITEntity<TT>
{
   public List<TT> Translate { get; set; }
}

public interface ILEntity
{
   public int LanguageId { get; set; }
}

public class FoodMenu : ITEntity<FoodMenuT>
{      
   public virtual List<FoodMenuT> Translate { get; set; } = new();
}

public class FoodMenuT :  ILEntity
{
   public int LanguageId { get; set; }
}

public static Expression<Func<T, IEnumerable<TT>>> LanguageFilter<T, TT>() where T : ITEntity<TT> where TT : ILEntity
{
   return e => e.Translate.Where(x => x.LanguageId == 1);
}
  • Related