0

我的 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。为什么这样?我不想再写过滤条件。有任何想法吗?

谢谢。

4

1 回答 1

1

您的查询不会返回每位客户的所有地址。它根本不返回任何地址。当您访问导航属性时,由于延迟加载,地址会在之后加载。这是第二次查询,延迟加载总是返回所有地址。

如果您想在单个数据库查询中获得所需的结果,您需要一个投影来在select操作中加载客户和地址。

利用你的导航属性(我猜,你有一些,因为你的问题下的标签),它看起来像这样:

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();

这不会填充客户对象树中的地址集合,而仅返回匿名对象列表:每个条目都有客户和该客户的过滤地址。

于 2012-03-31T19:53:44.963 回答