1

I wrote this SQL server select statement to only return 204 characters and append ... to the end if there was more than 204 chars in that row.

SELECT Name, Active, Image, CASE WHEN LEN(Description) <= 204 THEN Description ELSE LEFT (Description , 204) + '...' END AS 'Short Description' FROM Brands

How do I finish this linq code to do the same?

var query = db.Brands.Select(p=> new{
        Brand =p,
        p.Description.Length <-- I believe this is a starting point?>
    });

2 Answers 2

2

Well, the literal translation would be:

var query = db.Brands.Select(p => new {
        Brand = p,
        Description = p.Description.Length < 204 
                          ? p.Description 
                          : p.Description.Substring(0, 204) + "..."
    });

But I'd be surprised if that worked...

Is it absolutely crucial that you do this on the SQL side, rather than at the client? For example, this will work:

var query = db.Brands
              .AsEnumerable()
              .Select(p => new {
        Brand = p,
        Description = p.Description.Length < 204 
                          ? p.Description 
                          : p.Description.Substring(0, 204) + "..."
    });
Sign up to request clarification or add additional context in comments.

8 Comments

Is that the best way to do that? I included the SQL code just for an example of what I was trying to accomplish.
It says invalid anonymous type member declarator.
I don't think this will compile... you need to specify the property name explicitly (Description = ...) because the compiler can't infer it in that case
@Thomas, I believe you are correct, but I still am having trouble with the syntax.
Checked with Entity Framework (.Net 4.0) - it could translate it to SQL query. Finally it contained this in query CASE WHEN (( CAST(LEN([Extent1].[Text]) AS int)) > 10) THEN SUBSTRING([Extent1].[Text], 0 + 1, 10) ELSE [Extent1].[Text] END AS [C2]
|
0

The correct way to write it is as follows:

var query = db.Brands.Select(p=> new{
        Brand =p,
        c= p.Description.Length < 204 ? p.Description 
                               : p.Description.Substring(0, 204) + "..."
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.