amp
amp

Reputation: 12352

Concat strings in a projection (Linq)

How can I concat two string in a projection?

This is what I have so far:

IEnumerable<NameIdentity> data = null;
JsonResult res;
using (DBContext _db = new DBContext())
{
      data = MyEntity.GetEntities(_db).OrderBy(a=> a.name)
                    .Select(b=> new NameIdentity
                    {
                        ID = b.entityID,
                        Name = String.Join(" - ", new String[]{ b.year, b.name })
                    });
      res = Json(data.ToList(), JsonRequestBehavior.AllowGet);
 }

I need to concatenate the year and name properties in the Name propety of my projection.

The error that is giving me is an "NotSupportedException" that says that the LINQ to Entities doesn't recognize de Join() method and it cannot be translated to a store expression.

Upvotes: 0

Views: 1170

Answers (2)

Satpal
Satpal

Reputation: 133423

While you are using linq-to-entities you cannot use arbitrary .NET methods in query, You can use EdmFunctions, Here I have use EdmFunctions.Concat

data = MyEntity.GetEntities(_db).OrderBy(a=> a.name)
            .Select(b=> new NameIdentity
            {
                ID = b.entityID,
                Name = EdmFunctions.Concat(b.year, "-", b.name) 
            });

You can also use Canonical functions

Upvotes: 1

yo chauhan
yo chauhan

Reputation: 12315

 data = MyEntity.GetEntities(_db).OrderBy(a=> a.name)
                .Select(b=> new NameIdentity
                {
                    ID = b.entityID,
                    Name =  b.year +"-" + b.name
                });

Upvotes: 1

Related Questions