isedwards
isedwards

Reputation: 2499

String concatenation in dynamic-linq Select

I'm trying to return a new column that is the concatenation of id and name, with a hyphen inbeween, using dynamic-linq:

query.Select("new(id, name, id & " - " & name As idName")

But, I'm failing even to get simple concatenation working, even without the hyphen:

query.Select("new(id, name, id & name As idName")

This raises System.NotSupportedException

LINQ to Entities does not recognize the method System.String Concat(System.Object, System.Object) method, and this method cannot be translated into a store expression.

Is there any way around this, and if so, how would I also add the quoted section " - " to the expression in a way that dynamic-linq can interpret, also I'd like id and name to be variables as these change depending on the user's selection?

NOTE:

Upvotes: 3

Views: 2194

Answers (2)

Rafa Gomez
Rafa Gomez

Reputation: 710

If I understand you right this should work.

Imports System.Linq.Dynamic.Core

Dim col1 = "id"
Dim col2 = "name"

Dim results = query.Select($"new({col1} as {col1},
                                 {col2} as {col2},
                                 {col1} & "" - "" & {col2} as {col1}_{col2})")

There are maybe other ways, but you still will be only querying once the db, so it should be no problem I think.

Hope it helps...

Upvotes: 2

isedwards
isedwards

Reputation: 2499

The System.Linq.Dynamic NuGet package lists https://github.com/kahanu/System.Linq.Dynamic as the project page. Here, examples from Scott Guthrie's original 2008 blog on dynamic LINQ were being transferred over to the GitHub project's wiki, and the documentation was being extended.

However, looking through the issues list, the repository appears to be dead/dying (discussion here). Currently, the most active fork/NuGet package appears to be System.Linq.Dynamic.Core (which support .NET standard as well as .NET Core).

The documentation and examples in the original System.Linq.Dynamic are currently more extensive, but both wikis have a section on dynamic expressions and the expression language which include a section on operators. This includes concatenation:

x & y String concatenation. Operands may be of any type.

In my tests, concatenation works if you switch from the System.Linq.Dynamic NuGet package to the System.Linq.Dynamic.Core package (you don't have to be using .NET Core, it works with other versions of .NET as well).

Imports System.Linq.Dynamic.Core

query.Select("new(id & name As id_name)")

Upvotes: 3

Related Questions