views:

57

answers:

1

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
              });
A: 

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
          });
Lawrence
That does not feel right at all! Your code is selecting all DbAccount items, all DbMessage items and is doing the join using LinQ to objects. This has an impact on performance! To avoid the exception you should apply the ToList method call AFTER your join and perform the select using LinQ to objects.
Saintedlama