I am trying to assign data to a class, but when executing the method it shows me the 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 fields has an ICollection of the Message 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 to the TicketData class I obtain the values of the Ticket and 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 Message.
Then I manually assign the values with:
var TData = new TicketData()
{
IdTicket = detail.IdTicket,
IdUser = detail.IdUser,
Message = (ICollection<Message>)listMessages
};
But this is where it shows me the error described above. If I assign only the values of IdTicket and IdUser it works fine, but when I assign the listMessages to Message it displays the error.
Please can you tell me where I am failing, thank you.
CodePudding user response:
Although VMessage
may contain the same members as Message
, they are different and unrelated types, so you cannot cast from one to the other in C#.
What you need to do is convert each 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 regularly, you could always use a reflection-based mapping API to reduce boilerplate.