Search code examples
c#linq-to-entities

Unable to cast object of type '<>f__AnonymousType1`2 [System.Int64,System.String]' to type 'ConsoleApplication1.Profile'.


I very new to Linq and Entity frame work, i have problem with my below code. I am getting error

Unable to cast object of type '<>f__AnonymousType1`2 [System.Int64,System.String]' to type 'ConsoleApplication1.Profile'

.

My Code is:

static void Main(string[] args)
        {
            ProfileEntitiesContext obj = new ProfileEntitiesContext();
            List<Profile> list = new List<Profile>();
            var test = (from c in obj.Customer
                       join a in obj.Address
                       on c.ProfileId
                       equals a.Customer.ProfileId 
                       select new
                       {
                           CustomerProfileId = c.CustomerProfileId,
                           FirstName = c.FirstName
                   AddressLine1 = a.Line1   
                       }).ToList().Cast<CustomerConfidentialProfile>();

foreach(var cust in test) // Unable to cast object of type  '<>f__AnonymousType1`2
//[System.Int64,System.String]' to type 'ConsoleApplication1.Profile'.
            {
                list.Add(cust);
            }
        }

public class Profile
    {
        int _CustomerProfileId;
        string _FirstName;
        string _AddressLine1;


        public int CustomerProfileId
        {
            get { return _CustomerProfileId; }
            set { _CustomerProfileId = value; }
        }


        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; }
        }

  public string AddressLine1
        {
            get { return _AddressLine1; }
            set { _AddressLine1= value; }
        }
}

Any help will be appreciated.


Solution

  • Your problem is that from the LINQ-query you are returning a anonymous type ( by using the new { ... } syntax.

    However, you try to jam this object into a List<Profile>. So it's complaining that you are trying to put this anonymous object into a List that only takes Profile objects.

    Why just not replace new { ... with new Profile { ... since you are using the same fields in the anonymous type as you do in the Profile type.

    And remove ToList and Cast at the end as well.