使用Join with entity framework对象查询.Navigation属性仍然显示联接实体的所有实体
本文关键字:实体 显示 属性 entity with Join framework 对象 Navigation 查询 使用 | 更新日期: 2023-09-27 18:29:41
我的EF对象查询是:
from customer in MCDBContext.Customers
join customerCase in MCDBContext.CustomerCases on customer.CustomerID equals customerCase.CustomerID
join customerCasePhone in MCDBContext.CustomerCasePhones on customerCase.CustomerCaseID equals customerCasePhone.CustomerCaseID
**join customerCaseAddress in MCDBContext.CustomerCaseAddresses on customerCase.CustomerCaseID equals customerCaseAddress.CustomerCaseID**
where customer.CustomerPIN.Equals(pin, StringComparison.InvariantCultureIgnoreCase) &&
customerCasePhone.PhoneNumber.Equals(phoneNumber, StringComparison.InvariantCultureIgnoreCase) &&
**customerCaseAddress.AddressTypeID == 6** &&
customerCase.IsActive == true && customerCasePhone.IsActive == true && customerCaseAddress.Active == true && customer.IsActive == true
select customer;
代码中:
var customers = getmethod() //calls the above object query method.
现在,当我执行customers.First().CustomerAddresses();
//返回所有客户地址时,尽管我在对象查询中将其过滤为仅执行TypeID=6。为什么会这样?我不想再写筛选条件了。有什么想法吗?
谢谢。
您的查询不会返回每个客户的所有地址。它根本不返回任何地址。访问导航属性时,由于延迟加载,地址随后会被加载。这是第二个查询,延迟加载总是返回所有地址。
如果要在单个数据库查询中获得所需的结果,则需要在select
操作中加载客户AND地址的投影。
利用你的导航属性(我想,你有一些,因为你的问题下的标签),它看起来是这样的:
var result = MCDBContext.Customers
.Where(customer => customer.IsActive && customer.CustomerPIN.Equals(
pin, StringComparison.InvariantCultureIgnoreCase)
&& customer.CustomerCases.Any(ccase =>
ccase.IsActive
&& ccase.CustomerCasePhones.Any(phone =>
phone.IsActive
&& phone.PhoneNumber.Equals(
phoneNumber, StringComparison.InvariantCultureIgnoreCase))
&& ccase.CustomerCaseAddresses.Any(address =>
address.IsActive
&& address.AddressTypeID == 6)))
.Select(customer => new
{
Customer = customer,
// you can also fetch here cases and phones, if you need them
Addresses = customer.CustomerCases.Where(ccase => ccase.IsActive)
.Select(ccase => ccase.CustomerCaseAddresses
.Where(address => address.IsActive && address.AddressTypeID == 6))
})
.ToList();
这不会在客户的对象树中填充地址集合,而是只返回一个匿名对象列表:每个条目都有客户和该客户的过滤地址。