Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq equivalent of SQL LEFT function?

We have a database with some fields that are varchar(max) which could contain lots of text however I have a situation where I only want to select the first for example 300 characters from the field for a paginated table of results on a MVC web site for a "preview" of the field.

for a simplified example query where I want to get all locations to display in the table (this would be paginated, so I don't just get everything - I get maybe 10 results at a time):

return db.locations;

However this gives me a location object with all the fields containing the massive amounts of text which is very time consuming to execute.

So what I resorted to before was using SQL stored procedures with the:

LEFT(field, 300) 

to resolve this issue and then in the Linq to SQL .dbml file included the stored procedure to return a "location" object for the result.

However I have many queries and I don't want to have to do this for every query.

This maybe a simple solution, but I am not sure how I can phrase this on a search engine, I would appreciate anyone who can help me with this problem.

like image 364
CDrnly Avatar asked Dec 28 '22 21:12

CDrnly


1 Answers

You can use functions that directly translate to those functions too, this is useful when you need to translate code that functionally works just fine in SQL at no risk in LINQ. Have a look at System.Data.Objects.EntityFunctions

Locations.Select(loc=>System.Data.Objects.EntityFunctions.Left(loc.Field,300))

This will get directly translated into a LEFT on the server side.

like image 180
Ronan Thibaudau Avatar answered Jun 02 '23 12:06

Ronan Thibaudau