Using entity framework to convert guid to string

c# entity-framework


I've encountered a problem when attempting to transmit a GUID as a string through web services. In SQL Server, the GUID is kept as aUNIQUEIDENTIFIER EF then retrieves it as a GUID. I would want to include the following in my query:

var query = myEntities.Foo.Where(q => q.Id== Id)
                .Select(bar =>
                        new Bar()
                            { BString = bar.GUID }

The compilation fault that C# now gives prevents conversionSystem.Guid to string therefore I suppose you could do this:

{ BString = bar.GUID.ToString() }

and even

{ BString = Convert.ToString(bar.GUID) }

However, both come to a runtime exception:

There was an exception, it was System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String ToString(System.Object)' method, and this method cannot be translated into a store expression.

I thus infer that it is unable to determine a T-SQL equivalent of traveling fromUniqueIdentifier to varchar .

Is there an alternative to receiving the object, duplicating each item to a new object while iterating over my return set, and then converting guid->string at that point?


2/20/2012 4:02:24 PM

Accepted Answer

To make it a string, change the query portion of the LINQ expression to outside.

var query = myEntities.Foo.Where(q => q.Id== Id).Select(r => r.GUID)
  .Select(guid =>
    new Bar()
    { BString = guid.ToString() }

The .AsEnumerable() is crucial since it interprets the outcome ofIQueryable to IEnumerable causing any further activities to be performed on the client after the database query has been done. (You may also employ.ToArray() or .ToList() put it there.)

2/20/2012 3:46:52 PM

Popular Answer

You should definitely manually re-map your GUIDs to strings, like you mentioned, if speed is not an issue:

var query = from entity in myEntities.Foo
            where entity.Id == Id
            select new { GUID = entity.GUID };
var response = from item in query.ToList()
               select new Bar { BString = item.GUID }

While explicitly splitting into two requests, this is close to what @Tim Rogers advises.

I also consider creating a stored procedure that utilizes T-inherent SQL's ability to transform GUIDs to strings.convert() statement. This will get past EF's inability to automatically map GUIDs to strings.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow