0

I have the following view-model class inside my MVC application:-

public class CustomerDetails
    {   public AccountDefinition AccountDefinition {get; set;}
        public SDOrganization SDOrganization {get; set;}
        public IEnumerable<SiteDefinition> SiteDefinition { get; set; }
        public IEnumerable<AaaPostalAddress> AaaPostalAddress { get; set; }
        public IEnumerable<AaaContactInfo> AaaContactInfo { get; set; }
        public IEnumerable<SDUser> SDUser { get; set; }   }

Btu if i try to write this 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,
         SDUser = cd.SiteDefinitions.Select(p => p.UserSiteMappings.Select(p2 => p2.SDUser))//this is raising the error
       })
       .SingleOrDefault();
       return customerDetails;
        }

I will get the following error:-

Cannot implicitly convert type System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<TMS.Models.SDUser>> to System.Collections.Generic.IEnumerable<TMS.Models.SDUser>. An explicit conversion exists (are you missing a cast?)

So what is wrong with my code??

4

1 回答 1

2

Due to the way generics are implemented in Java, you can use a generic type like List<E> without giving the generic arguments (e.g. just List). C# does not work this way, so the type you gave in the title of this question (System.Collections.Generic.IEnumerable) doesn't actually exist. The actual question here is:

Why is converting System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<TMS.Models.SDUser>> to System.Collections.Generic.IEnumerable<TMS.Models.SDUser> considered an error.

The answer is similar to the reason you can't assign an object of type int[,] to a variable of type int[]. Perhaps you meant to use SelectMany instead of Select on the line that is reporting the error. This "flattens" the individual results to produce a single enumeration that contains all of the elements from each individual sub-result.

SDUser = cd.SiteDefinitions.SelectMany(
    p => p.UserSiteMappings.Select(p2 => p2.SDUser))
于 2013-07-09T11:18:39.857 回答