can't select into class using linq

Yannick Smits picture Yannick Smits · Aug 12, 2009 · Viewed 7.6k times · Source

I have a query that works fine when using an anonymous type but as soon as I try to un-anonymize it it fails to select all values into the class.

here is the linq i'm using (in combination with Subsonic 3):

var producten = (from p in Premy.All()
     join pr in Producten.All() on p.dekking equals pr.ID
     where p.kilometragemax >= 10000 &&
           p.CCmin < 3000 &&
           p.CCmax >= 3000 &&
           p.leeftijdmax >= DateTime.Today.Subtract(car.datumEersteToelating).TotalDays / 365
     group p by new { pr.ID, pr.Naam, pr.ShortDesc, pr.LongDesc } into d
     select new
     {
         ID = d.Key.ID,
         Dekking = d.Key.Naam,
         ShortDesc = d.Key.ShortDesc,
         LongDesc = d.Key.LongDesc,
         PrijsAlgemeen = d.Min(x => x.premie),
         PrijsAlgemeenMaand = d.Min(x => x.premie),
         PrijsMerkdealerMaand = d.Min(x => x.premie),
         PrijsMerkdealer = d.Min(x => x.premie)
     }).ToList();

When I change it to:

List<QuotePremies> producten = (from p in Premy.All()
     join pr in Producten.All() on p.dekking equals pr.ID
     where p.kilometragemax >= 10000 &&
           p.CCmin < 3000 &&
           p.CCmax >= 3000 &&
           p.leeftijdmax >= DateTime.Today.Subtract(car.datumEersteToelating).TotalDays / 365
     group p by new { pr.ID, pr.Naam, pr.ShortDesc, pr.LongDesc } into d
     select new QuotePremies
     {
         ID = d.Key.ID,
         Dekking = d.Key.Naam,
         ShortDesc = d.Key.ShortDesc,
         LongDesc = d.Key.LongDesc,
         PrijsAlgemeen = d.Min(x => x.premie),
         PrijsAlgemeenMaand = d.Min(x => x.premie),
         PrijsMerkdealerMaand = d.Min(x => x.premie),
         PrijsMerkdealer = d.Min(x => x.premie)
     }).ToList();

in combination with this class:

public class QuotePremies
{
    public byte ID { get; set; }
    public string Dekking { get; set; }
    public string ShortDesc { get; set; }

    public string LongDesc { get; set; }
    public decimal PrijsAlgemeen { get; set; }
    public decimal PrijsAlgemeenMaand { get; set; }
    public decimal PrijsMerkdealer { get; set; }
    public decimal PrijsMerkdealerMaand { get; set; }
}

it doesn't give me an error but all values in the class are 0 except for QuotePremies.ID, QuotePremies.ShortDesc and QuotePremies.LongDesc. No clue why that happens.

Answer

shahkalpesh picture shahkalpesh · Aug 12, 2009

See if using conversion helps

PrijsAlgemeen = Convert.ToDecimal(d.Min(x => x.premie))