Linq equivalent of SQL LEFT function?

前端 未结 3 1539
离开以前
离开以前 2021-01-19 10:48

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 c

相关标签:
3条回答
  • 2021-01-19 11:15

    I found something like this worked 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 a a different object, but it seems to work.

    0 讨论(0)
  • 2021-01-19 11:16

    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.

    0 讨论(0)
  • 2021-01-19 11:18

    EDIT: I misread LEFT for LTRIM. Here's all the String functions that can't 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 an excellent article with screen shots showing you how to do so.

    If you're not using the designer tool you can also call ExecuteCommand against the DataContext. It isn't pretty, but it's what we have for now.

    0 讨论(0)
提交回复
热议问题