Get information about Predicate <T>

I have an interface similar to the following:

public IEnumerable<IDocument> Search(Predicate<IDocument> predicate) { ... }

where the IDocument looks like this:

public interface IDocument 
{
    string Id {get; set;}
    string Title {get; set;}
    ...
}

I am going to implement a document provider where I need to decompose the contents of a Predicate and retrieve properties in order to create an SQL string for a document database to which we currently do not have an OR / M mapping. Example: I want to know if a user is searching by ID or by title, so I know if I can search by ID or search LIKE in the header.

I have always used LINQ heavily, but this is the first time I'm sitting at the other end of the pipeline ... I read the expression trees and Reflection a bit, but the parts haven't fallen the place yet. How (if?) I can decompose / flip Predicate, so I get a list of parameters that I can concatenate into an SQL string? I am looking for something like this rough sketch:

public IEnumerable<IDocument> Search(Predicate<IDocument> predicate) 
{ 
    string id = DoSomeMagic(predicate, "Id");
    string title = DoSomeMagic(predicate, "Title");
    if (!string.isNullOrEmpty(id))
       ...make ID search
    else
       ...search by title
}

Disclaimer: the provider is intended for an outdated internal system related to the replacement this fall, which makes the correct SQL query correct, o)

+3
source share
3 answers

You cannot easily understand a predicate. Perhaps you should consider changing your design to a more specific type of predicate, a more specific predicate interface:

    public interface IDocument 
    {
        string Id {get; set;}
        string Title {get; set;}
    }
    public class SearchCriteria
    {
        public Nullable<int> Id;
        public string Title;
    }
    public IEnumerable<IDocument> Search(SearchCriteria predicate)
    {
        if (predicate.Id.HasValue)
            //...make ID search
        else if (!string.IsNullOrEmpty(predicate.Title))
            //...search by title
        else
            // other kind of search
    }

, SearchCriteria (,.GetResult() .GetSQLQuery()), , , .

+1

. , , . Expression, . O/RM.

Expression LINQ to SQL, , :

public IEnumerable<Document> Search(
    Expression<Func<Document, bool>> predicate) 
{
    using (db = new DocumentDataContext())
    {
        return db.Documents.Where(predicate).ToArray();
    }
}
+3

> . ( , ).

LinqPad (LinqPad Dump, )

void Main()
{
    show(x=>x.Length==5);
}

void show(Expression<Predicate<string>> e){
    e.Dump();
}

, Compile first

0
source

Source: https://habr.com/ru/post/1736113/


All Articles