Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting guid to string with entity framework

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.

like image 971
Dio Avatar asked Oct 24 '25 15:10

Dio


1 Answers

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.)

like image 87
Tim Rogers Avatar answered Oct 26 '25 04:10

Tim Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!