Linq to entities and CAST

We use an EDMX to access our database with Entity Framework. Before you comment: we have our reasons not to use code-first. Today we encountered a small problem with linq to entities and validating a varchar field that contains an integer value. Again: we have our reasons. Think about key-value pairs.

An excellent answer of Joel Mueller on helped us overcome this problem. In short we had to add a function to our edmx conceptual model. The link above has all te details.

<Function Name="ParseInt" ReturnType="Edm.Int32">
   <Parameter Name="stringvalue" Type="Edm.String"/>
      CAST(stringvalue as Edm.Int32)

The validation works like a charm now. This is what EF generates (see the CAST?):

SELECT [GroupBy1].[A1] AS [C1]
        FROM [dbo].[Table] AS [Extent1]
        WHERE ([Extent1].[Key] = @p__linq__0) 
        AND (( CAST( [Extent1].[Value] AS int) < @p__linq__1) 
          OR ( CAST( [Extent1].[Value] AS int) > @p__linq__2))
    )  AS [GroupBy1]

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.