简体   繁体   English

where 子句中连接表的表达式树

[英]Expression tree for Joined Tables in where-clause

I joined two tables Collection and Pictures and created this class:我加入了两个表 Collection 和 Pictures 并创建了这个 class:

namespace Example.Models
{
    public class CollectionNPictures
    {
        public Collection Collection { get; set; }
        public Pictures Pictures { get; set; }
    }
}

I created a query:我创建了一个查询:

var SQL = from collection in _context.Collection
          join pictures in _context.Pictures
          on collection.Nummer equals pictures.Nummer
          select new CollectionNPictures { Collection = collection, Pictures = pictures };

I want to create a dynamic where-clause (like loop over predicate = predicate.And(c=> c.Collection.columnName.Contains(searchValues)))我想创建一个动态 where 子句(如循环谓词 = predicate.And(c=> c.Collection.columnName.Contains(searchValues)))

How can I solve this?我该如何解决这个问题?

I solved it this way:我是这样解决的:

var predicate = PredicateBuilder.New<CollectionNPictures>();
predicate = predicate.And(GenericPredicates.CreatePredicateStringContainsJoin("Collection", "Ort", Orte));

public static Expression<Func<CollectionNPictures, bool>> CreatePredicateStringContainsJoin(string table, string columnName, ICollection<string> searchValues)
{
    var predicateloc = PredicateBuilder.New<CollectionNPictures>();
    var eParam = Expression.Parameter(typeof(CollectionNPictures), "c");
    var method = typeof(string).GetMethod("Contains", new Type[] { typeof(string) });
    if(method is null)
        return predicateloc;

    foreach (string searchValue in searchValues)
    {
        if (!string.IsNullOrWhiteSpace(searchValue))
        {
            var call = Expression.Call(Expression.Property(Expression.Property(eParam, table), columnName), method, Expression.Constant(searchValue));
            var lambda = Expression.Lambda<Func<CollectionNPictures, bool>>(call, eParam);
            predicateloc = predicateloc.Or(lambda);
        }
    }

    return predicateloc;

}
SQL = SammlungSQL.Where(predicate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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