Zachary Scott
Zachary Scott

Reputation: 21198

Entity Framework 4: How to code projection to a class type?

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?

Upvotes: 4

Views: 2342

Answers (2)

Steve
Steve

Reputation: 2093

Another option is to create a CustomerInfo type:

public class CustomerInfo
{
  public int Id { get; set;}
  public string Name { get; set; }
}

You can't map two types directly to the same table in EF but you can easily create a view for your info type and then map to that:

CREATE VIEW vwCustomerInfo AS SELECT Id, Name FROM Customer

You then map your CustomerInfo type to your view:

public class CustomerInfoMap : EntityConfiguration<CustomerInfo>
{
  public CustomerInfoMap()
  {
    .ToTable("vwCustomerInfo");
  }
}

A side-effect of this is that EF will only retrieve the columns in the view when querying your database. When retrieving a CustomerInfo by id you'll get SQL like this:

SELECT Id, Name FROM vwCustomers WHERE id = 1

In addition, as long as your view is updatable you can update your CustomerInfo type from EF and the underlying table will be updated.

Upvotes: 0

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102448

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".

Upvotes: 2

Related Questions