Exception thrown when retrieving data from database when grouping

67 Views Asked by At

I'm trying to retrieve accounting periods from a MySql database using entity framework but keep running into an InvalidCastException exception.

This is the linq statement below:

var periodList = (from pd in _context.perioddates
                 join p in _context.periods on pd.PeriodId equals p.PeriodId
                 orderby pd.PeriodDate1 descending
                 group new { p, pd } by p.PeriodId into pdg
                 select pdg.FirstOrDefault()).ToList();

This query should give me a list of periods and their start dates, leaving out their period end dates. However it throws the following:

TargetInvocationException: 'Exception has been thrown by the target of an invocation

The inner exception being:

InvalidCastException: Specified cast is not valid.

This exception was originally thrown at this call stack: MySql.Data.MySqlClient.MySqlDataReader.GetByte(int)

The period table is Modeled as follows:

public partial class period
{
    public byte PeriodId { get; set; } // TinyInt Unsigned
    public long Period1 { get; set; } // Int Unsigned
    public string PeriodName { get; set; } // VarChar
}

And the period table looks like this:

public partial class perioddate
{
    public int PeriodDateId { get; set; } // SmallInt Unsigned
    public DateTime PeriodDate1 { get; set; } // DateTime
    public byte VariantId { get; set; } // Tiny Int
    public byte PeriodId { get; set; } // Tiny int
}

Can anyone tell me why it's throwing this exception? Why would it have a problem drawing tinyints from the db when using grouped data and load perfectly fine when pulling info straight? I'm a bit baffled at this.

Much appreciated in advance.

Edit:

When I say 'pulling straight' I mean a query that pulls all records from the database as is, without a group. In this instance, that would be:

var periodList = (from pd in _context.perioddates
                  join p in _context.periods on pd.PeriodId equals p.PeriodId
                  orderby pd.PeriodDate1 descending
                  select new PeriodModel()
                  {
                      PeriodId = p.PeriodId,
                      Period = p.Period1,
                      PeriodDateId = pd.PeriodDateId,
                      PeriodDate = pd.PeriodDate1
                  }).ToList();

This query will work but it includes closing dates as well.

0

There are 0 best solutions below