如何编写这个 linq 查询以避免太多查询?

发布于 2024-09-13 03:43:26 字数 346 浏览 4 评论 0原文

我有两张表“公司”和“员工”。其中关系是公司(一个) - 员工(多个)。
我想将所有员工的姓名连接到一个字符串并输出。 我知道我可以写这样的查询:

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

就此别过 2024-09-20 03:43:26
var employeeNames = context
                       .Company
                       .Where(c => c.Id = 0xF00)
                       .SelectMany(c => c.Employee)
                       .Select(e => e.Name)
                       .ToArray();

var result = String.Join(" ", employeeNames);

您可以根据确切的语义和实体框架版本稍微改变选择公司的查询部分。在 .NET 4.0 中,实体框架支持 Single()。如果您不关心细微的语义差异,则可以在 .NET 4.0 之前使用 First() 而不是 SelectMany()

var employeeNames = context
                       .Company
                       .Where(c => c.Id = 0xF00)
                       .SelectMany(c => c.Employee)
                       .Select(e => e.Name)
                       .ToArray();

var result = String.Join(" ", employeeNames);

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 use First() instead of SelectMany() prior to .NET 4.0.

痴梦一场 2024-09-20 03:43:26

这是丹尼尔的简化变体,但我认为它应该有效(对模式做出假设)

var employeeNames = (from e in context.Employee
                       where e.CompanyId = 0xF00
                       select e.Name)
                       .ToArray(); 

var result = String.Join(" ", employeeNames); 

This is a simplified variation of Daniel's but I think it should work (making assumptions about the schema)

var employeeNames = (from e in context.Employee
                       where e.CompanyId = 0xF00
                       select e.Name)
                       .ToArray(); 

var result = String.Join(" ", employeeNames); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文