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

LINQ code returns an anonymous type, how can I return a strong "Clients" type? I am returning an anonymous type as I only want to select specific fields from the object.

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

+6
source share
2 answers

Or 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 client instances using 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(); 

create new client instances with only those properties that you are interested in filling out. (if the client class has a constructor without parameters)

+6
source

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

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

If only one (or possibly none) of these clients uses SingleOrDefault() only to get a single Customer object:

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

Source: https://habr.com/ru/post/898031/


All Articles