Search code examples
c#linqdapper

C# Adding items to object list field


I've two class Agens and OrdiniPuddy. There is a relationship among them by mean codAge field.

 public class Agens
    {
        public string COD_CG { get; set; }
        public string codAge { get; set; }
        public string Agente { get; set; }
        public string Societa { get; set; }

        public DateTime PrimaTrasm { get; set; }
        public DateTime UltimaTrasm { get; set; }

        public int Destinazioni { get; set; }
        public int Pezzi { get; set; }
        public double Imponibile { get; set; }

      public List<OrdiniPuddy> ordiniPuddy { get; set; }
    }



public class OrdiniPuddy
    {
        public string codCli { get; set; }
        public string Dest_ID { get; set; }

        public string Ragsoc { get; set; }
        public string Indirizzo { get; set; }
        public string Localita { get; set; }
        public string Prov { get; set; }
        public string Regione { get; set; }
        public string Calendario { get; set; }
        public string Cap { get; set; }
        public string codAgente { get; set; }

    }

I've populated them with this code:

var results = connection.QueryMultiple(sql);
 IEnumerable<Agens> agenti = results.Read<Agens>();
 IEnumerable<OrdiniPuddy> ordiniP = results.Read<OrdiniPuddy>();

Last step is to passing ordiniP to agenti.ordiniPuddy by mean AddRange Linq method like this

foreach (var item in agenti)
            {
                 
               IEnumerable <OrdiniPuddy> ordini = ordiniP.Where(o => o.codAgente == item.codAge).ToList();
                  agenti.ordiniPuddy.AddRange((IEnumerable<Agens>)ordini); 
            }

but the compiler give me a error message on agenti.ordiniPuddy: 'type' does not contain a definition for 'name' and no accessible extension method 'name' accepting a first argument of type 'type' could be found (are you missing a using directive or an assembly reference?).

Where is the error, why I can't referencing agenti.ordiniPuddy? My C# knowledge are at beginning. Thank's


Solution

  • Fix your code

    var ordini = ordiniP.Where(o => o.codAgente == item.codAge).ToList();
    
    if(ordini!=null) 
    {
     if( item.ordiniPuddy ==null)  item.ordiniPuddy=new List<OrdiniPuddy>();
    item.ordiniPuddy.AddRange(ordini); 
    }