Unable to cast object of type System.Collections.Generic.List to type System.Collections.Generic.ICollection

Unable to cast object of type System.Collections.Generic.List to type System.Collections.Generic.ICollection

Questions : Unable to cast object of type System.Collections.Generic.List to type System.Collections.Generic.ICollection

752

I am trying to assign data to a class, but in4codes_linq when executing the method it shows me the in4codes_linq error:

Unable to cast object of type 'System.Collections.Generic.List to type 'System.Collections.Generic.ICollection 

The procedure I am doing is the following:

I have the TicketData class, which among its in4codes_linq fields has an ICollection of the Message in4codes_linq class.

public partial class TicketData { public int IdTicket { get; set; } public int? IdUser { get; set; } public ICollection<Message> Message { get; set; } } 

To assign the values in4codes_linq ​​to the TicketData in4codes_linq class I obtain the values in4codes_linq ​​of the Ticket and in4codes_linq Message class.

public class Ticket { public int IdTicket { get; set; } public int? IdUser { get; set; } } public class Message { public int IdTicket { get; set; } public int? IdMessage { get; set; } public string Text { get; set; } } 

I do this with the following methods:

var detail = await _unitOfWork.TicketsRepository.GetDetailsTicketRepository(Id); var messageService = await _unitOfWork.MessageRepository.GetMessagesTicketRepository(Id); List<VMessages> listMessages = messageService.ToList(); 

Inside VMessages is identical to class in4codes_linq Message.

Then I manually assign the values in4codes_linq ​​with:

var TData = new TicketData() { IdTicket = detail.IdTicket, IdUser = detail.IdUser, Message = (ICollection<Message>)listMessages }; 

But this is where it shows me the error in4codes_linq described above. If I assign only the values in4codes_linq ​​of IdTicket and in4codes_linq IdUser it works fine, but when I assign the in4codes_linq listMessages to Message it displays the in4codes_linq error.

Please can you tell me where I am failing, in4codes_linq thank you.

Total Answers 1
27

Answers 1 : of Unable to cast object of type System.Collections.Generic.List to type System.Collections.Generic.ICollection

Although VMessage may contain the same in4codes_linq members as Message, they are different in4codes_linq and unrelated types, so you cannot cast in4codes_linq from one to the other in C#.

What you need to do is convert each in4codes_linq VMessage to a Message.

One way is to use LINQ:

var convertMessages = listMessages.Select(x => new Message { IdTicket = x.IdTicket, IdMessage = x.IdMessage, Text = x.Text, }); var TData = new TicketData() { IdTicket = detail.IdTicket, IdUser = detail.IdUser, Message = convertMessages.ToArray(), }; 

If this is something that you need to do in4codes_linq regularly, you could always use a in4codes_linq reflection-based mapping API to reduce in4codes_linq boilerplate.

0