我可以在Linq to SQL中使用C#字符串插值吗 [英] Can I use C# string interpolation with Linq to SQL
问题描述
在使用EF(至少是6.1.3版之前)的情况下,假设您拥有这样的类:
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; }
}
如果要获取作为查询结果中字段(FirstName
和LastName
)的并置的字段FullName
,则必须执行以下操作:
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 })
现在C#中存在字符串插值,您可以改成这样吗
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?
推荐答案
我不希望如此,不.它将编译为string.Format
调用,我不会期望得到支持.如果您确实需要在SQL部分中完成投影,则可以对其进行测试...,否则,通常,在完成所需查询部分后,请使用AsEnumerable()
在数据库中执行,然后使用Select
:
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}");
这篇关于我可以在Linq to SQL中使用C#字符串插值吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!