在 entity framework 预测方面需要帮助
Need help on entity framework projections
我有两个实体:客户和地址
CUSTOMER
---------
Id
Name
Addresses
ADDRESS
---------
Id
CustomerId
Street
City
Country
IsPrimaryAddress
客户可以有多个地址,但只有一个主地址。
我只需要获取客户列表及其主要地址。如何通过一次调用数据库获取它?
只需创建一个不是实体的新类型,然后return根据您的查询:
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();
}
我有两个实体:客户和地址
CUSTOMER
---------
Id
Name
Addresses
ADDRESS
---------
Id
CustomerId
Street
City
Country
IsPrimaryAddress
客户可以有多个地址,但只有一个主地址。 我只需要获取客户列表及其主要地址。如何通过一次调用数据库获取它?
只需创建一个不是实体的新类型,然后return根据您的查询:
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();
}