LINQ查询以选择特定数据

时间:2019-01-21 02:42:09

标签: c# performance entity-framework linq

我正在尝试编写查询,该查询将仅返回我需要在视图中显示的特定信息。

我有以下代码:

var companiesWithResponsibleUser = from company in ctx.Companies
   join user in ctx.Users on company.ResponsibleUserId equals user.Id
   group new { company, user } by company.Id into g
   select new
   {
       company = g.Select(t => t.company),
       user = g.Select(t => t.user)
   }; 

但是,这一次从两个表中返回完整数据,这非常慢。我只需要公司名称,公司表中的地址,负责的用户ID和用户表中的全名。

我该如何重写此查询,以便仅用我想要的数据填充这两个对象?

2 个答案:

答案 0 :(得分:2)

以下内容应为您提供帮助:

var companiesWithResponsibleUser  = from company in ctx.Companies
       join user in ctx.Users on company.ResponsibleUserId equals user.Id
       group new { company, user } by company.Id into g
       select new
       {
           companyname = g.company.CompanyName
           address= g.company.Address,
           userid = g.user.UserId,
           fullname= g.user.FullName
       };

请注意,我尚未对此进行测试。

答案 1 :(得分:1)

我不确定,但是您可以尝试以下方法:

var companiesWithResponsibleUser = (from company in ctx.Companies
                                               join user in ctx.Users on 
                                   company.ResponsibleUserId equals user.Id
                                   select company.CompanyName,company.Address,user.Userid,user.UserFullName).ToList();


var Res = (from x in companiesWithResponsibleUser
  group x by new
  {
      x.CompanyName,
      x.Userid
  } into g
  select new {g.key.CompanyName, g.Address,g.key.Userid,g.UserFullName}).ToList();

如果发生错误,您可以添加此部分g.Address

  x.CompanyName,
  x.Userid,
  x.Address

如果select中不存在该字段,则用户g.key.Address