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
    }
}
Maslow
  • 18,464
  • 20
  • 106
  • 193

1 Answers1

1

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
  • 182,639
  • 35
  • 285
  • 343