Using entity framework to convert guid to string

c# entity-framework

Question

I'm trying to pass a GUID as a string over web services, however I've hit a bump in the road. The GUID is stored in SQL Server as a UNIQUEIDENTIFIER and EF pulls it as a GUID. What I would want to do is in my query do this:

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

Now, C# throws a build error that you cannot convert System.Guid to string, so I'd think that you could do this:

{ BString = bar.GUID.ToString() }

or even

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

But both end with 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.

So I gather that in both cases, it's not able to figure out a T-SQL equivalent of going from UniqueIdentifier to varchar.

Is there a way around this besides retrieving the object, then iterating over my return set copying each object to a new object and converting guid->string at that point?

Thanks.

1
3
2/20/2012 4:02:24 PM

Accepted Answer

Convert it to a string outside the query part of the LINQ statement.

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

The .AsEnumerable() is the important part: it casts the result from IQueryable to IEnumerable, having the effect of running any further operations on the client after the database query has been made. (You could also use .ToArray() or .ToList() in its place.)

6
2/20/2012 3:46:52 PM

Popular Answer

If performance isn't a concern, you probably should re-map your GUIDs to strings manually, as you suggested yourself:

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 }

This is similar to what @Tim Rogers suggests, but explicitly split into two queries.

Another option I come up with is writing a stored procedure that converts GUIDs to strings using the T-SQL's native convert() statement. This will work around EF's inability to map GUIDs to strings automatically.



Related Questions





Related

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