Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Converting Enum to String in LINQ Query

I have the following query, which is using Entity Framework.

Analytic firstSent = (from a in Repository.Query<Analytic>()
                      where a.EntityType == "Proposal" &&
                      a.EntityId == Program.ActiveProposal.Id &&
                      a.Marker == AnalyticMarker.EmailProposalUrl.ToString()
                      orderby a.TimestampUtc
                      select a).FirstOrDefault();

At run time, I get the following error:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

a.Marker is a string column, and AnalyticMarker.EmailProposalUrl is an enum value, and I want to compare that column against the name of that enum.

I understand that the conversion from an enum to a string is not supported by SQL, but why won't it resolve the value of this string and then pass the resulting string to SQL? That should work just fine.

like image 447
Jonathan Wood Avatar asked Jan 28 '13 20:01

Jonathan Wood


1 Answers

Try this:

var emailProposalUrl = AnalyticMarker.EmailProposalUrl.ToString();
Analytic firstSent = (from a in Repository.Query<Analytic>()
                      where a.EntityType == "Proposal" &&
                      a.EntityId == Program.ActiveProposal.Id &&
                      a.Marker == emailProposalUrl
                      orderby a.TimestampUtc
                      select a).FirstOrDefault();

This other answer is explaining the reason why this could work as well..

The problem arises because ToString() isn't really executed, it is turned into a MethodGroup and then parsed and translated to SQL. Since there is no ToString() equivalent, the expression fails.

like image 163
Hari Pachuveetil Avatar answered Oct 23 '22 20:10

Hari Pachuveetil