我正在寻找优化我的 LINQ 查询,因为虽然它工作正常,但它生成的 SQL 是复杂且低效的......
基本上,我希望选择订购所需产品 (reqdProdId) 并使用信用卡号注册的客户(作为 CustomerDisplay 对象)(使用外键 CustId 存储为 RegisteredCustomer 表中的一行)
var q = from cust in db.Customers
join regCust in db.RegisteredCustomers on cust.ID equals regCust.CustId
where cust.CustomerProducts.Any(co => co.ProductID == reqdProdId)
where regCust.CreditCardNumber != null && regCust.Authorized == true
select new CustomerDisplay
{
Id = cust.Id,
Name = cust.Person.DisplayName,
RegNumber = cust.RegNumber
};
总而言之,客户有一个相应的人,该人具有名称;PersonID 是 Customer 表中的外键。如果我查看生成的 SQL,我会看到从 Person 表中选择了所有列。仅供参考,DisplayName 是使用 Customer.FirstName 和 LastName 的扩展方法。有什么想法可以限制来自 Person 的列吗?
其次,我想摆脱 Any 子句(并使用子查询)来选择具有所需 ProductID 的所有其他 CustomerId,因为它(可以理解)生成 Exists 子句。您可能知道,LINQ 有一个与联结表有关的已知问题,所以我不能只做一个 cust.CustomerProducts.Products。如何选择联结表中具有所需 ProductID 的所有客户?
任何帮助/建议表示赞赏。