简体   繁体   中英

Linq C# method syntax, join 3 tables

I'm working on an ASP.NET C# WebApi with linq.

I have this three tables: clients, contacts and departments. In "contacts" table I just save the "id (departamento)" from the department that the contact belong, so in my view i need to show the "description (nombre)". What I have now is the following:

Tables:

在此处输入图像描述

Controller:

        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;
    }

With this I get the information of the client and the contacts but deparment is showing just the id. What I'm trying to accomplish is this sql query:

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    

Let me know if I'm missing some information, thanks a lot!

SOLVED

As @VadimBondaruk said, just needed to add this line:

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

Thanks!

You can convert to LINQ as

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
                 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM