-2

I have a query turns out that I have to do a filter joining two tables with lambda, is the expression with only one but how do I do it with two?

this is my SQL Query

    declare @Cod_Empresa int
set @Cod_Empresa = 9
select 
Margen.Codigo_Medidor, Margen.Fecha, Margen.Codigo_barra, Margen.Total_Balance
from tb_margen_operativo_cierre Margen, tb_medidor Medi
where Margen.Codigo_medidor = Medi.Codigo_Medidor
and Medi.Codigo_empresa  = @Cod_Empresa

This is my C# Code

 int codigoempresa = 9 
 var margen = cm.tb_margen_operativo_cierre. //I need 2 tables tb_margen_operativo_cierre and tb_medidor
             Where(x => x.Fecha <= fin && x.Fecha >= inicio).
            GroupBy(r => r.Fecha).
            Select(v => new
            {

                Total_Balance = v.Sum(x => x.Total_Balance),

            }).AsEnumerable().Select(x => new tb_margen_operativo_cierre
            {

                Total_Balance = x.Total_Balance,


            }).ToArray();
            for (int i = 0; i < margen.Length; i++)
            {

                valormes = valormes + margen[i].Total_Balance;
                valorgraficodiario[i] = margen[i].Total_Balance;
            }

How do it? thanks

6
  • Your LINQ code is not even close to the SQL you posted. I don't see any grouping nor date filtering on the SQL query. Are you sure you posted the correct code? Commented Jul 19, 2018 at 18:09
  • Take a look in Here see if it helps Commented Jul 19, 2018 at 18:13
  • What is this? EF? Linq to SQL? Do you have any Navigation Properties, could we see your Entities (at least tb_margen_operativo_cierre) Commented Jul 19, 2018 at 18:14
  • You Can use Like this My example: stackoverflow.com/questions/30977089/asp-net-mvc-5-entity-join/… Commented Jul 19, 2018 at 18:15
  • Perhaps my SQL to LINQ Recipe would help you? Commented Jul 19, 2018 at 21:48

1 Answer 1

1

Well, first one, you have to improve your query, to something like this:

SELECT 
    Margen.Codigo_Medidor, Margen.Fecha, Margen.Codigo_barra, Margen.Total_Balance
FROM 
    tb_margen_operativo_cierre Margen INNER JOIN tb_medidor Medi
ON 
    Margen.Codigo_medidor = Medi.Codigo_Medidor
WHERE 
    Medi.Codigo_empresa  = 9;

Now, if you have relations between your tables, you can do this in LINQ:

Asuming: One Margen could have Many Medi. In LinQ you might use:

from Margen tb_margen_operativo_cierre 
join Medi in tb_medidor on Margen.Codigo_medidor equals Medi.Codigo_Medidor
where Medi.Codigo_empresa == 9;

And the result should be the same of your query.

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

1 Comment

I think you meant equals and not = in the LINQ for join and == and not = for the where.

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.