• Sun. Sep 29th, 2024

C# – Get list of rows that satisfy condition in query join

Byadmin

Dec 11, 2021

I’m new to using queries inside C# code so i need a little help over here.

I have these 2 tables in my db:

public class ItemTPRetencionPMD
    {

        public DateTime? FechaAprobacion { get; set; }
        public int IdPedido { get; set; }
        public int NroPedido { get; set; }
        public string Codigo { get; set; }
        public string CodigoCompania { get; set; }
        public string Retencion { get; set; }

        public ItemTPRetencionPMD()
        {
        }

    }

 public class ItemTPSalesOrdPMD
    {

        public string SalesDocument { get; set; }
        public string BriefcaseNumber { get; set; }
        public string MaterialNumber { get; set; }
       
        public ItemTPSalesOrdPMD()
        {
        }
    }

And i have another class that contains a list of ItemTPRetencionPMD and a list of ItemTPSalesOrdPMD:

 public class TrackingProductoPMD
      {
            public int NroPedidoBrief { get; set; }
            public long NroPedido { get; set; }
    
            [NotMapped]
            public List<ItemTPRetencionPMD> Retenciones { get; set; }
    
            [NotMapped]
            public List<ItemTPSalesOrdPMD> SalesOrds { get; set; }
    
            public TrackingProductoPMD()
            {
                SalesOrds = new List<ItemTPSalesOrdPMD>();
                Retenciones = new List<ItemTPRetencionPMD>();
            }
    
     }

Now, i want make a query that returns rows of the “TrackingProductoPMD” table, and i also need it to include both the “Retenciones” and the “SalesOrds” lists. This query has left outer joins, so i can still get the “TrackingProductoPMD” item even if any of the lists ends up being empty:

 var query = from prod in dbBrief.TrackingProductoPMD
                        join r in db.ItemTPRetencionPMD on prod.NroPedidoBrief equals r.NroPedido into itemConRetenciones
                        from retenciones in itemConRetenciones.DefaultIfEmpty()
                        join so in db.ItemTPSalesOrdPMD on prod.NroPedido equals Convert.ToInt64(so.SalesDocument) into itemConSalesOrds
                        from salesOrds in itemConSalesOrds.DefaultIfEmpty()
                        select new { prod, retenciones, salesOrds };

These are the conditions in my query:

TrackingProductoPMD.NroPedido == ItemTPSalesOrd.SalesDocument
TrackingProductoPMD.NroPedidoBrief == ItemTPRetencion.NroPedido

Here’s the problem i’m having: The “ItemTPSalesOrdPMD” and the “ItemTPRetencionPMD” tables can have multiple rows that coincide with the condition, but i’m only obtaining a single row in each of them. And they are being treated as single items instead of lists. I need to get all rows that satisfy the conditions i put in the query as lists.

How can i modify my query to accomplish that?

By admin