Friday, November 30, 2007

Linq to Sql and Enums - Unexpected Behavior - Part 2

In my previous post, I mentioned the first set of unexpected behavior I ran into with Linq to Sql and Enums. Here's the next one:

So the RoleProvider wants an array of strings the represents the names of all the Roles a given user is in. So here's the Linq code that I wrote to do that:

return (from u2r in lMainDataContext.User2Roles
where u2r.User.EmailAddress == username
select u2r.RoleTypeEnum.ToString()).ToArray();

The problem, the array that was returned contained the value "2".

Why, because Linq to Sql tries to convert this query to Sql and execute it using the database engine.

The problem is that RoleTypeEnum is an int as far as the database engine is concerned and so it returns a string representation of that int, instead of "Partner" which is what I was expecting.

Splitting the query into two forces Linq to Sql to map the int to an enum:

RoleType[] lMatchingRoles = (from u2r in lMainDataContext.User2Roles
where u2r.User.EmailAddress == username
select u2r.RoleTypeEnum).ToArray();

return lMatchingRoles.Select(r => r.ToString()).ToArray();

Another place where you realize that SQL Server doesn't really know about enums.

1 comment:

Anonymous said...

Concern Fresh Wind offers a invest money in building for different tariff plans. Now , survivors overcame the recent financial crisis, more began to wonder where to invest money . According to conclusions of many of the leading the best analysts, one of the most real estate investment . It is no secret Everyone knows that the construction of less exposed to the risk of falling prices, in addition , property has always enjoyed , and will be in demand. Even the economic crisis did not recaptured removed the desire for people to buy their own property. Therefore, investment in construction will always remain relevant and profitable. [url=]where to invest your money at interest[/url]