4
votes

How can I convert this query to linq to entities with entity framework:

SELECT  customer_id,
    customer_name,
    customer_code
FROM dbo.V_STF_CUSTOMER
WHERE   company_id=@company_id AND
ORDER BY    CASE
            WHEN ISNUMERIC(customer_name)=1 THEN 1
            ELSE 0
        END,
        customer_name

I have this:

return CUstomers.GetQuery().
            Where(x => x.CompanyId == companyId).
        OrderBy(??This is my problem??);

I don't know how to translate the orderby. Any idea?

3

3 Answers

8
votes
return Customers.GetQuery().
            Where(x => x.CompanyId == companyId).
        OrderBy(x=> SqlFunctions.IsNumeric(x.customer_name)).
        ThenBy(x=> x.customer_name);
1
votes

You can use SqlFunctions.IsNumeric in your query to map to IsNumeric in Sql Server.

Something along the lines of:

        var results = from c in customers
                      where c.companyId = companyId
                      orderby SqlFunctions.IsNumeric(c.customerName) == 1 ? 1 : 0, c.customerName
                      select new { c.customerId, c.customerName, c.customerCode };
0
votes

First I think there something wrong with the SQL query in

WHERE   company_id=@company_id AND

why you added AND ?

you can achieve ISNUMERIC in Entity Framewwork only (not linq to sql) by using SqlFunctions.IsNumeric

return CUstomers.GetQuery().
            Where(x => x.CompanyId == companyId).
            OrderBy(x => SqlFunctions.IsNumeric(x.customer_name)).
            ThenBy(x => x.customer_name);