如何编写这个 linq 查询以避免太多查询?
我有两张表“公司”和“员工”。其中关系是公司(一个) - 员工(多个)。
我想将所有员工的姓名连接到一个字符串并输出。 我知道我可以写这样的查询:
String names = "";
foreach(var emp in Company.Employee)
{
names += emp.name;
}
但是如果我使用这个意思,我会将所有员工记录加载到内存中,然后进行比较,这既浪费时间又浪费内存,并且会降低性能。 那么在 linq 中,是否可以设计这样一个查询,可以在单个 SQL 中返回所有串联名称?
提前致谢 !任何建议将不胜感激!
I have two table Company and Employee. And there relation is Company(one) - Employee(many).
And I want to concatenate all the Employees' name to a string and output.
I know I can write such a query :
String names = "";
foreach(var emp in Company.Employee)
{
names += emp.name;
}
But If I use this mean, I would load all the employee records into memory, and then make comparison, which is a waste of time and memory, and would low the performance.
So in linq, is it possible to craft such a query that can return all concatenated names within a single SQL ?
Thanks in advance ! Any recommendations will be greatly appreciated !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以根据确切的语义和实体框架版本稍微改变选择公司的查询部分。在 .NET 4.0 中,实体框架支持
Single()
。如果您不关心细微的语义差异,则可以在 .NET 4.0 之前使用First()
而不是SelectMany()
。You can vary the part of the query selecting the company a bit depending on the exact semantics and Entity Framework version. In .NET 4.0 the Entity Framework supports
Single()
. If you don't care about minor semantic differences you can useFirst()
instead ofSelectMany()
prior to .NET 4.0.这是丹尼尔的简化变体,但我认为它应该有效(对模式做出假设)
This is a simplified variation of Daniel's but I think it should work (making assumptions about the schema)