Ingmar
Ingmar

Reputation: 67

LINQ: Convert Guid to string

I am getting an exception when I execute this code:

var result = from menu in menuBus.GetMenus()
             orderby menu.InternalName
             select new 
             {
                 Value = menu.ID.ToString(),
                 Text = menu.InternalName
             };

var result = allMenus.ToList();

The error message says: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a stored expression.

So, I guess that something goes wrong with Value = menu.ID.ToString(). The ID property is defined as GUID (UniqueIdentifier in MS SQL).

Does anybody have a solution for this?

Thank you very much!!!

Upvotes: 4

Views: 7308

Answers (2)

George Polevoy
George Polevoy

Reputation: 7671

You need to run the list through another query after querying the database.

var result = (from menu in menuBus.GetMenus()
                        orderby menu.InternalName
                        select new 
                        {
                            Value = menu.ID,
                            Text = menu.InternalName
                        }).ToList();


var result2 = (from menu in result select new {Value=menu.Value.ToString(),Text=menu.Text}).ToList();

Upvotes: 7

Ivan Crojach Karačić
Ivan Crojach Karačić

Reputation: 1911

As far as I know you can't have .ToString() in your linq query because linq to entity doesn't know what to do with it (because it can't convert it to an sql statement)... You can have the select part as

select new
{
     Value = menu.ID,
     Test = menu.InternalName
}

and then just user a foreach loop and copy the values into another list while converting the guid to string

Upvotes: 1

Related Questions