2

For every table (and I have a lot of them) I provide Lookup REST API method in my ASP.Net Core application.

This is part of my query for every table:

    context.Users.Select(t => new ViewLookupModel()
    {
        id = t.Id,
        title = t.DisplayName
    })
    //......
    context.Groups.Select(t => new ViewLookupModel()
    {
        id = t.Id,
        title = t.Name
    })

But I want to write extension to shrink code I need to write for every table. Something like this:

        public static IQueryable<ViewLookupModel> SelectLookup<T>(this IQueryable<T> query, Func<int> idField, Func<string> titleField)
        {
            return query.Select(t => new ViewLookupModel()
            {
                id = idField(),
                title = titleField()
            });
        }

And use case:

context.Users.SelectLookup(t => t.Id, t => t.DisplayName)
//......
context.Groups.SelectLookup(t => t.Id, t => t.Title)

But I get error:

Delegate 'Func' does not take 1 arguments.

This and this question seems similar, but I can not get it to work.

I am also interesting in any performance issues when querying database with custom SELECT extension method.

Makla
  • 9,899
  • 16
  • 72
  • 142

1 Answers1

2

Change your extension method to this and try. Extension method takes T as input and returns the corresponding int or string etc.

public static IQueryable<ViewLookupModel> SelectLookup<T>(this IQueryable<T> query, Func<T,int> idField, Func<T,string> titleField)
    {
        return query.Select(t => new ViewLookupModel()
        {
            id = idField(t),
            title = titleField(t)
        });
    }
Ayaz
  • 2,111
  • 4
  • 13
  • 16
  • 1
    This cannot be translated to SQL, hence doesn't work in EF6 and earlier (runtime exception), and in EF Core will cause client evaluation, hence is inefficient. – Ivan Stoev Sep 07 '17 at 09:48