Can I use C # string interpolation with Linq to SQL

When using EF (at least until version 6.1.3), if you have a class like this:

class Customer { public string FirstName { get; set; } public string LastName { get; set; } } 

if you get a FullName field which is a concatenation of both ( FirstName and LastName ) as a field as a result of the query, you will need to do something like this:

 db.Customers.Select(c => new { FullName = c.FirstName + " " + c.LastName }) 

now that there is String Interpolation in C #, you could do something like this instead

 db.Customers.Select(c => new { FullName = $"{c.FirstName} {c.LastName}" }) 

this may seem like a trivial example (as it is), but the question remains.

Can I use this out of the box, do I need to do some tricks to make it work, or is it sure it won’t work?

+8
c # linq entity-framework
source share
2 answers

I would not expect this, no. It will be compiled before calling string.Format , which I would not expect to be supported. If you really need a projection in the SQL part, you can test it ... but otherwise, as usual, use AsEnumerable() when you finish the part of the query that you must execute in the database, and then use Select after that :

 var query = db.Customers // Project to just the properties we need .Select(c => new { c.FirstName, c.LastName }) // Perform the rest of the query in-process .AsEnumerable() .Select(c => $"{c.FirstName} {c.LastName}"); 
+12
source share

You could do something like this instead

Not in a general sense, because string interpolation is simply translated into a call to string.Format , replacing placeholders with numbers and passing values ​​as parameters. Therefore, your format is translated from

 $"{c.FirstName} {c.LastName}" 

to

 string.Format("{0} {1}", c.FirstName, c.LastName); 

Since not all string.Format() functions string.Format() user-format strings, indentation, alignment, etc.) can be directly translated into SQL, they are not supported.

Do I need to do some tricks to make it work, or is it sure it won't work?

I doubt there are any tricks you can do to make it work in Ling-to-SQL, since you are dealing with string.Format internally. You can get all the necessary fragments, call AsEnumerable to change the context from Linq-to-SQL to Linq-to-Objects, and then use interpolation in the subsequent projection, but in this trivial case, using string concatenation is cleaner.

+5
source share

All Articles