0

Good day to all, I have the following problem I have to convert the following query SQL to LINQ to SLQ or lambda expression:

SELECT  T2.ID, SUM(T1.Importe) AS Importe, T3.ID, T3.Column_1,
        T3.Column_2, T1.Column_3
FROM    Tabla_1 T1
INNER JOIN Tabla_2 T2 on T1.ID = T2.ID
INNER JOIN Tabla_3 T3 on T2.ID = T3.ID
WHERE   T1.ID in (LIST)
GROUP BY T2.ID, T3.ID, T3.Column_1, Column_2, T1.Column_3

where LIST is a List (12,15,18,19,...)

as performed in linq or lamnbda expression?

thks!

2
  • Start off small. Make one inner join and get that working for you, make a simple grouping and then put it all together. Commented Apr 2, 2012 at 22:58
  • Convert sql to linq/lambda sentence Commented Apr 2, 2012 at 22:58

2 Answers 2

3

Here is the hint:

var result = ents.T1
    .Where(x => list.Contains(x.Id))
    .GroupBy(x => new 
                 { 
                    Id2 = x.T2.Id, 
                    Id3 = x.T3.Id,
                    ...
                    // etc group fields 
                 })
    .Select(x => new
                 { 
                    Importe = x.Sum(i => i.Importe)
                    x.Key.Id2,
                    // other group fields
                    ...
                 })
    .ToArray();

I strongly suggest not to name columns and tables the way you did. Really)

Sign up to request clarification or add additional context in comments.

2 Comments

the field "Importe" exist in the GroupBy clause?
Importe exists in each element of Grouping. So you can use Sum over it.
1

I did not try, but it could look like that :

var result = (from t1 in dataContext.tabla_1
              join t2 in dataContext.tabla_2 on t1.ID equals t2.ID
              join t2 in dataContext.tabla_2 on t2.ID equals t3.ID
              group t2 by t2.ID into g
              where listIds.contains(t1.ID)
              select new {g.ID, g.Sum(t => t.Importe), ...});

3 Comments

var result = (from t1 in dataContext.tabla_1 join t2 in dataContext.tabla_2 on t1.ID equals t2.ID join t2 in dataContext.tabla_2 on t2.ID equals t3.ID where listIds.contains(t1.ID) group t2 by t2.ID into g select new {g.ID, g.Sum(t => t.Importe), ...}); LINQ to Entities does not recognize the method 'Boolean Contains(Int32)' method, and this method cannot be translated into a store expression.
It is the same function as The_Smallest's answer. Is it working in his example?
no work, exception message: "LINQ to Entities does not recognize the method 'Boolean Contains(Int32)' method, and this method cannot be translated into a store expression" thks anyway =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.