views:

149

answers:

1

I get an InvalidCastException converting a linq entity list to a businessobject list using the .Cast<> operator. "Unable to cast object of type 'Ticketing.ticket' to type 'Ticketing.ModelTicket'." (namespace name was changed because underscore was causing unneeded formatting)

here's my business object class

public sealed class ModelTicket
{
public ModelTicket(ticket ticket)
 {
  _Ticket = ticket;
 }
public static implicit operator ModelTicket(ticket item)
 {
  return new ModelTicket(item);
 }
}

and here's my extension method to convert a list of linq objects to a list of business objects:

public static class ModelTicketExtensions
{
 public static List<ModelTicket> ToModelTickets(this List<ticket> list)
 {
  return list.Cast<ModelTicket>().ToList();// exception on cast
 }
}
+1  A: 

I would go with the following function:

public static class ModelTicketExtensions
{
    public static List<ModelTicket> ToModelTickets(this List<ticket> list)
    {
        return list.ConvertAll<ModelTicket>(t => (ModelTicket)t);
    }
}

If that doesn't work for you, then you can go the completely direct route:

public static class ModelTicketExtensions
{
    public static List<ModelTicket> ToModelTickets(this List<ticket> list)
    {
        return list.ConvertAll<ModelTicket>(t => new ModelTicket(t));
    }
}

I'd say the second is arguable more clear on exactly what is happening.

Adam Robinson
yeah I found ConvertAll and wound up going with number 2, thanks.
Maslow