views:

48

answers:

1

I have some table that contains annual sequence data in column like "1/2010", "2/2010" or "13/2010". I want to order data from this table by this column. So I should create order value for sorting like that the following SQL expression.

-- This code should work if amount of data is less than 1000 record per year.
CAST(SUBSTRING(ReceiveID, 0, CHARINDEX('/', ReceiveID)) AS INT) + 1000 * CAST(SUBSTRING(ReceiveID, CHARINDEX('/', ReceiveID) + 1, 4) AS INT)  AS OrderReceiveID

However, I want to write this code with EF 4.0 but I got some a few problems.

First, I try to create order expression in LINQ query. But I cannot call string to integer convert function like “int.Parse” because it cannot convert this to SQL statement.

Secondly, I create scalar-value function in database for converting string of annual sequence data to integer like “1/2010” to 20100001. But I cannot import it to edmx file because it supports only stored procedure.

Finally, I create custom view for this table, including custom order column (for data like 2010001) and I use additional column to order this table. Everything works well. But I don't like this because I don't need to create one view per one table.

Do you any idea for solving this problem without touch the database or create shared function for converting sequence data to integer value like my second idea?

Thanks,

A: 

You can try to use the ExecuteStoreQuery method.
In this case you will be able to use the mentioned method for sorting (and execute any other native SQL).
The code will look like:


  var q = context.ExecuteStoreQuery("SELECT ReceiveID, SomeField, SomeOtherField, ...  from Model1.MyEntity order by CAST(SUBSTRING(ReceiveID, 0, CHARINDEX('/', ReceiveID)) AS INT) + 1000 * CAST(SUBSTRING(ReceiveID, CHARINDEX('/', ReceiveID) + 1, 4) AS INT)");
Devart
Yes. I know but this way will create a non-strongly-typed query in my project that is unacceptable for me. Moreover, I must check/validate this query every time after I change column in database, instead of sync edmx file and build.
Soul_Master
You can use the context.ExecuteStoreQuery<MyEntityType> overload to get strongly-typed ObjectResult<MyEntityType>. But you will have to check the query every time your database schema is changed, unfortunately.
Devart