我有两个实体:客户和地址
CUSTOMER
---------
Id
Name
Addresses
ADDRESS
---------
Id
CustomerId
Street
City
Country
IsPrimaryAddress
客户可以拥有多个地址,但只能有一个主要地址。 我需要获取客户列表及其主要地址。如何通过一次调用数据库来获取它?
答案 0 :(得分:2)
只需创建一个非实体的新类型,然后从查询中返回:
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();
}