This is something that has bugged me since the shift to EF 6. How do we now map collections through to view models such that mapping changes back are not painful using IEnumerables. Here is a code snippet below demonstrating my problem:
Entity - SS.Entity.Event
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SS.Entity.User> Broadcasters { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SS.Entity.User> Viewers { get; set; }
Model - SS.Model.Event
public virtual ICollection<SS.Model.User> Broadcasters { get; set; }
public virtual ICollection<SS.Model.User> Viewers { get; set; }
Mapping Back to Entity After Modification of Collection
Broadcasters = e.Broadcasters.Select(u => new SS.Entity.User
{
Id = u.Id,
SkypeId = u.SkypeId,
Name = u.Name
}).ToList(), // THIS IS THE PROBLEM
Viewers = e.Viewers.Select(u => new SS.Entity.User
{
Id = u.Id,
SkypeId = u.SkypeId,
Name = u.Name
}).ToList() // THIS IS THE PROBLEM
The problem with this is I cannot map an ICollection to another ICollection as Select produces an IEnumerable which makes mapping back properties to EF afterwards a pain as I have to recreate the collection or enumerate it to update it. I know I'm missing something obvious, I have updated the ICollection's to be virtual as outlined in other answers but it is unclear to me how this helps.
Any help would be greatly appreciated!
Gerard