Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.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
                       };

Thanks

like image 342
mark s Avatar asked Sep 26 '11 00:09

mark s


2 Answers

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)

like image 58
Bala R Avatar answered Nov 02 '22 16:11

Bala R


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();
like image 30
BrokenGlass Avatar answered Nov 02 '22 18:11

BrokenGlass