Linq equivalent to SQL LEFT function?

We have a database with some fields that are varchar (max) that can contain a lot of text, however I have a situation where I want to select only the first 300 characters from a field for a broken table of results on the MVC website for "preliminary view 'fields.

for a simplified query example where I want all locations to appear in a 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 huge amounts of text, which are very laborious to execute.

So, to what I turned to earlier, SQL stored procedures were used with:

 LEFT(field, 300) 

to solve this problem, and then a stored procedure is included in the Linq to SQL.dbml file to return a location object for the result.

However, I have many requests, and I do not want to do this for each request.

It may be a simple solution, but I'm not sure how I can indicate it in a search engine, I would be grateful to anyone who can help me with this problem.

+4
source share
3 answers

EDIT: I read LEFT incorrectly for LTRIM . Here are all String functions that cannot be used in LINQ to SQL . Have you tried String.Substring() ?

Your best option is to map the stored procedure and continue using it. Here is a great article with screen shots showing you how to do this.

If you are not using the constructor tool, you can also call ExecuteCommand in the DataContext . This is not very, but it is what we have now.

+3
source

You can use functions that directly jump to these functions, this is useful when you need to translate code that works fine in SQL functionally without any risks in LINQ. Take a look at System.Data.Objects.EntityFunctions

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

This will be directly translated to server side LEFT .

+4
source

I found something like this for me:

 return from locationPart in db.locations select new LocationPart { Description = locationPart.description, Text = locationPart.text.Substring(0,300) }; 

Not ideal, because I have to use "select new" to return another object, but it seems to work.

+1
source

All Articles