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

时间:2011-09-26 00:22:27

标签: 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
                       };

由于

2 个答案:

答案 0 :(得分: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;

使用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();

仅使用您感兴趣的属性创建新客户实例。 (如果客户类有无参数构造函数)

答案 1 :(得分:2)

看起来您正在寻找与contractNo匹配number的任何合同的所有客户 - 请勿使用联接,而是使用EF导航属性:

var customers = _entities.Customers
                         .Where( c => c.Contracts.Any( x => x.contractNo == number));

如果这些客户只有一个(或可能没有),请使用SingleOrDefault()来检索单个Customer实体:

Customer customer = _entities.Customers
                             .Where( c => c.Contracts.Any( x => x.contractNo == number))
                             .SingleOrDefault();