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();
精彩评论