views:

34

answers:

1

If I have a class like the following:

public class Customer {
    public int    id    {get;set;}
    public string name  {get;set;}
    public string line1 {get;set;}
    public string line2 {get;set;}
    public string line3 {get;set;}
    public string line4 {get;set;}
}

And I only want to select the ID and Name values, leaving the rest null.

var myCustomerList = DC.Customer.Select( 
                     p => new Customer { id = p.id, name = p.name });

I get the following error:

The entity or complex type 'MyModel.Customer' cannot
be constructed in a LINQ to Entities query.

How else would you do it? Am I required to specify all the Class's fields?

+1  A: 

Try this:

var myCustomerList = from c in DC.Customer 
                     select new { id = p.id, name = p.name };

The above will create an Anonymous Type.

Practical Application:

"var myCustomerList" <-- Anonymous Type.

An anonymous type with two properties "id" and "name". Also, "var" lets you create an Implicitly typed local variable. This means:

a) You didn't have to declare/write a class structure to hold a type with only those two properties;

b) You don't have to maintain that either - you can change the structure of the above query, and "it just works".

Leniel Macaferi
Say you want to return the strongly typed object where the rest of the fields are null? I used your advice, then looped through the anonymous object feeding a new List<Customer> so my repository didn't need a ton of ViewModel classes defined.
Dr. Zim
I looped through the records because I am not always sure how many fields will be in the domain model (if they add more).
Dr. Zim