Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
923 views
in Technique[技术] by (71.8m points)

entity framework - Can I use C# string interpolation with Linq to SQL

While using EF (up to version 6.1.3 at least) assuming you have a class like this:

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

if you to get a field FullName that is the concatenation of both (FirstName and LastName) as a field in query result you would have to do something like this:

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

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

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

this might seem like a trivial example (which it is) but the question remains.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wouldn't expect so, no. It'll compile down to a string.Format call, which I wouldn't expect to be supported. If you really need the projection to be done in the SQL part, you could test it... but otherwise, as normal, use AsEnumerable() when you've finished the part of the query you need to be performed 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}");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...