Search code examples
c#nest

Invalid Generic Type with NEST


I have this method i want to make Generic type. This would allow the method to accept any class Model I pass in for exaple Blog model, Post Model, Author Model etc.

So that, anytime I call this method, i would just pass in the Model and query.

public T SearchIndex(T model, string query)
{
    var srchService = client.Search<model>(s => s
    .Query(q => q
        .Match(m => m.Query("hello"))
    ));

    return T;
}

I am using NEST from elasticsearch. I want to avoid repeating code for All the models. from the above, T => T is a type which is not valid in this context.


Solution

  • Your code is pretty wrong. You are mixing types and variables.
    Specifically, T is a type and you can't return types. And model is a variable and you can't use variables as generic type parameters.

    Maybe you want this?

    public T SearchIndex<T>(string query)
    {
        return client.Search<T>(s => s
        .Query(q => q
            .Match(m => m.Query("hello"))
        ));
    }