开发者

EF4 how can I convert anonymous type to strong type in LINQ

开发者 https://www.devze.com 2023-04-08 04:00 出处:网络
The LINQ code returns a anonymous type how can I return a strong type of \"Customers\"? I am returning a anonymous type as I only want to select certain fields from the entity.

The LINQ code returns a anonymous type how can I return a strong type of "Customers"? I am returning a anonymous type as I only want to select certain fields from the entity.

var customer = from c in _entities.Customers
                           join con
                           in _entities.Contracts on c.CustomerID equals con.cu开发者_C百科stomerID
                           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
                       };

Thanks


Either do

var customer = from c in _entities.Customers
                       join con
                       in _entities.Contracts on c.CustomerID equals con.customerID
                       where con.contractNo == number
                       select c;

to select the customer instances with as-is or

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

to create new instances of customer with just the properties you are interested in filled out. (provided customer class has a parameterless constructor)


It looks like you are looking for all customers that have any contract with a contractNo that matches number - don't use a join, instead use the EF navigation property:

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

If there is just a single (or possibly none) of these customers use SingleOrDefault() to just retrieve a single Customer entity:

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

精彩评论

暂无评论...
验证码 换一张
取 消