user4593252
user4593252

Reputation: 3506

Code Conversion: EF.OrderBy as a string works in VB but not in C#

filter.OrderBy is a string. It is assumed you will put in the name of a column.

query is defined as follows:

    Dim query As IQueryable(Of MyEntityFrameworkClass) = context.Set(Of MyEntityFrameworkClass)()

filter is a POCO that exposes a few properties of various primitive types.

In VB, this works:

    If filter.OrderBy <> "" Then query = query.OrderBy(filter.OrderBy)

The same code in C#:

if (!String.IsNullOrEmpty(filter.OrderBy) {query = query.OrderBy(filter.OrderBy);}

causes the following compiler error:

The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I get it that VB gets all loosey-goosey on what it will allow but what is a good conversion for this in C#???

Upvotes: 1

Views: 83

Answers (1)

ocuenca
ocuenca

Reputation: 39356

The method you need to use is OrderBy extension method of IQueryable<T>. To use those extension methods you need to reference System.Linq namespace.

This method receive as parameter Expression<Func<TSource, TKey>>, so to call it you need to do something like this:

Dim query As IQueryable(Of MyEntityFrameworkClass) = context.Set(Of MyEntityFrameworkClass)()
var result= query.OrderBy(Function(x) x.SomeProperty)

Where SomeProperty is a property of MyEntityFrameworkClass entity class

Upvotes: 1

Related Questions