HJ1990
HJ1990

Reputation: 415

How to return a IEnumerable<object> with LINQ Query

I am trying to return an IEnumerable when I use a LINQ Query expression but it throws an error. However, if I use a lambda expression it works perfectly fine. I'm confused as to why the LINQ Query does not work.

public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerID { get; set; }
        public string CustomerName { get; set;}
        public string CustomerAddress { get; set; }
        public string CustomerPhoneNumber { get; set; }
    }




  public  IEnumerable<Customer>GetAllCusterNames()
 {

            var query = (IEnumerable<Customer>)from cust in 
                         mycontext.Customers
                        select new { cust.CustomerID, cust.CustomerName };

            // lambda expression works perfectly fine
            //var query = mycontext.Customers.Select(p => new Customer
            //{
            //    CustomerID = p.CustomerID,
            //    CustomerName = p.CustomerName
            //});

            return query;
 }

Upvotes: 1

Views: 2610

Answers (1)

Nan Yu
Nan Yu

Reputation: 27588

That error occurs because anonymous type (i.e. the thing you create with select new {...} construct) cannot be cast to a named type.

You can use below codes instead:

var query = (IEnumerable<Employee>)from cust in
            db.Employees
            select new Employee { Id = cust.Id, Name = cust.Name };

Upvotes: 1

Related Questions