I have two entities: Customer and address
CUSTOMER
---------
Id
Name
Addresses
ADDRESS
---------
Id
CustomerId
Street
City
Country
IsPrimaryAddress
Customer can have multiple address but only one primary address. I need to get a list of customers along with its primary address only. How can i get it with a single call to the database?
Just create a new type that is not an entity and return this from your query:
using (var db = new YourDbContext())
{
var results =
from customer in db.Customers
let primaryAddress = customer.Addresses.Single(a => a.IsPrimaryAddress)
select new CustomerQueryResult
{
Id = customer.Id,
Name = customer.Name,
Address = primaryAddress
};
return results.ToArray();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.