Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Collections.Generic.ICollection

StackOverflow https://stackoverflow.com/questions/17545062

  •  02-06-2022
  •  | 
  •  

Question

I have defiend the following model class inside my asp.net mvc wen application:-

public class CustomerDetails
{
    public AccountDefinition AccountDefinition {get; set;}
    public SDOrganization SDOrganization {get; set;}
    public ICollection<SiteDefinition> SiteDefinition { get; set; }
    public ICollection<AaaPostalAddress> AaaPostalAddress { get; set; }
    public ICollection<AaaContactInfo> AaaContactInfo { get; set; }
    public virtual ICollection<UserSiteMapping> UserSiteMapping { get; set; } 
}

Then i write the following query:-

var customerDetails = entities.AccountDefinitions
    .Where(a => a.ORG_ID == id)
    .Select(cd => new CustomerDetails
    {
        AccountDefinition = cd,
        SDOrganization = cd.SDOrganization,
        AaaPostalAddress = cd.SDOrganization.AaaPostalAddresses,
        AaaContactInfo = cd.SDOrganization.AaaContactInfoes,
        SiteDefinition = cd.SiteDefinitions,
        UserSiteMapping = cd.SiteDefinitions.Select(p2 => p2.UserSiteMappings) //this is raising the exception
    })
    .SingleOrDefault();

return customerDetails;

But i got the following misleading error :-

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable>' to 'System.Collections.Generic.ICollection'. An explicit conversion exists (are you missing a cast?)

I do not know exactly what is causing the error, as i am selecting the UserSiteMapping related to a SiteDefinition , and i am assigning these to a collection of UserSiteMapping (as defined inside my view model)????

Was it helpful?

Solution

Use SelectMany instead:

UserSiteMapping = cd.SiteDefinitions.SelectMany(p2 => p2.UserSiteMappings)

You may also need ToList() or ToArray() call to switch from IEnumerable<T> to ICollection<T>:

UserSiteMapping = cd.SiteDefinitions.SelectMany(p2 => p2.UserSiteMappings).ToList()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top