EF4如何在LINQ中将匿名类型转换为强类型

mar*_*k s 6 entity-framework linq-to-sql

LINQ代码返回匿名类型如何返回强类型的"客户"?我正在返回一个匿名类型,因为我只想从实体中选择某些字段.

var customer = from c in _entities.Customers
                           join con
                           in _entities.Contracts on c.CustomerID equals con.customerID
                           where con.contractNo == number
                           select new
                           {
                               Surname = c.Surname,
                               Forename= c.Forename,
                               Address = c.Address,
                               Suburb = c.Suburb,
                               State = c.State,
                               Postcode = c.PostCode,
                               PhoneNo = c.PhoneNo
                       };
Run Code Online (Sandbox Code Playgroud)

谢谢

Bal*_*a R 6

要么这样做

var customer = from c in _entities.Customers
                       join con
                       in _entities.Contracts on c.CustomerID equals con.customerID
                       where con.contractNo == number
                       select c;
Run Code Online (Sandbox Code Playgroud)

使用as-is或选择客户实例

Customer customer = (from c in _entities.Customers
                       join con
                       in _entities.Contracts on c.CustomerID equals con.customerID
                       where con.contractNo == number
                       select new Customer{
                           Surname = c.Surname,
                           Forename= c.Forename,
                           Address = c.Address,
                           Suburb = c.Suburb,
                           State = c.State,
                           Postcode = c.PostCode,
                           PhoneNo = c.PhoneNo
                       }).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

仅使用您感兴趣的属性来创建新客户实例.(提供的客户类有一个无参数构造函数)