【问题标题】:Linq C# method syntax, join 3 tablesLinq C#方法语法,连接3个表
【发布时间】:2020-08-12 17:55:42
【问题描述】:

我正在使用 linq 开发 ASP.NET C# WebApi。

我有这三个表:客户、联系人和部门。在“联系人”表中,我只保存联系人所属部门的“id(departamento)”,所以在我看来,我需要显示“描述(名词)”。我现在拥有的是以下内容:

表格:

控制器:

        public clientes GetById(int id)
    {
        projectEntities context = null;
        clientes result = null;

        try
        {
            context = GetContext();
            result = context.clientes
                .Include(e => e.clientes_contactos)
                .FirstOrDefault(e => e.cve_cliente == id);
        }
        catch (Exception exception)
        {
            throw exception;
        }
        finally
        {
            context?.Dispose();
        }

        return result;
    }

有了这个,我得到了客户和联系人的信息,但部门只显示了 id。 我想要完成的是这个 sql 查询:

select a.*, b.*, c.nombre from clientes as a inner join clientes_contactos as b on a.cve_cliente = b.cve_cliente inner join cat_departamentos as c on b.departamento = c.cve_departamentos where a.cve_cliente = 2006    

如果我遗漏了一些信息,请告诉我,非常感谢!

已解决

正如@VadimBondaruk 所说,只需要添加这一行:

.Include(e => e.clientes_contactos.Select(cc => cc.cat_departament))

谢谢!

【问题讨论】:

  • 试试这个:result = context.clientes .Include(e => e.clientes_contactos) .ThenInclude(cc => cc.cat_departament).FirstOrDefault(e => e.cve_cliente == id);
  • 谢谢,我已经尝试过了,但这无效,因为 cat_department 与客户没有关系。它只有与联系人。 @VadimBondaruk
  • 您使用哪个版本的实体框架?
  • 现在是 6.2.0 @VadimBondaruk
  • .Include(e => e.clientes_contactos.Select(cc => cc.cat_departament))

标签: c# linq asp.net-web-api


【解决方案1】:

您可以转换为 LINQ 为

var query = (from a in context.clientes 
        join b in context.clientes_contactos on a.cve_cliente equals b.cve_cliente
        join c in context.cat_departamentos on b.departamento  equals c.cve_departamentos
                 where a.cve_cliente == 2006
                 select new {
                     a = a,
                     b = b,
                     c = c
                 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多