Select new to create complex object with nested new throws cast exception

163 Views Asked by At

Has anyone had this issue? I am trying to get objects from the database and create a complex poco but I get a cast issue.
The Account property on the poco message type is a poco account type and it will tell me that whatever the first field type is can't be cast to PocoAccount, so in the example below, AccountID is an int so i'll get int cant' be cast to PocoAccount.

var result = (from a in DbAccount.All()
              join m in DbMessage.All() on m.AccountID equals a.AccountID
              select new PocoMessage {
                Account = new PocoAccount {
                  AccountID = a.AccountID,
                  FirstName = a.FirstName,
                  LastName = a.LastName
                },
                MessageID = m.MessageID,
                Subject = m.Subject,
                Body = m.Body
              });
1

There are 1 best solutions below

1
On

If found a similar post that suggested using ToList() which seems to fix the issue however it doesn't feel quite right and I haven't checked out the sql consequence.

var result = (from a in DbAccount.All().ToList()
          join m in DbMessage.All().ToList() on m.AccountID equals a.AccountID
          select new PocoMessage {
            Account = new PocoAccount {
              AccountID = a.AccountID,
              FirstName = a.FirstName,
              LastName = a.LastName
            },
            MessageID = m.MessageID,
            Subject = m.Subject,
            Body = m.Body
          });