如何使用方法语法从多个表中获取数据而不使用连接,但只使用.where()方法?
我正在针对EF5 db上下文进行选择,该上下文映射到此遗留表结构,其中我有一个人员详细信息表,另一个表引用自身以创建层次结构,并以这种方式引用人员详细信息表:
PersonSet
.Where(p => p.LastName.ToLower()=="surname")
.Join(SubsetSet, p => p.Id, ss => ss.SubsetLink, (p, ss) => new { PersonDetail = p, person = ss })
.Where(m => m.person.Frame=="a" && m.person.Purpose=="1")
.Join(SubsetSet, ss1 => ss1.person.Owner, person => person.SubsetLink, (ss1, ss2) => new { person = ss1, club = ss2 })
.Where(a => a.club.Frame=="b" && a.club.Purpose=="2")
.Join(SubsetSet, ss => ss.club.Owner, ss2 => ss2.SubsetLink, (ss, ss2) => new { club = ss, association = ss2 })
.Where(a => a.association.Frame=="b" && a.association.Purpose=="3")
.Join(SubsetSet, ss => ss.association.Owner, ss3 => ss3.SubsetLink, (ss, ss3) => new { association = ss, district = ss3})
.Where(d => d.district.Frame=="b" && d.district.Purpose=="4" && d.district.SubsetLink=="12345")
.Select(proj => new { proj.association.club.person, proj.association.club, proj.association, proj.district })
.OrderByDescending(a => a.association.club.person.phyperson.FirstName)
.Take(10).Dump();
上述查询至少在LinqPad中起作用,但在我看来,如果我能摆脱这些连接,那么语句看起来可能会更好一些。现在我知道,就像下面的Albahari示例一样,这可以通过查询语法来完成。但我找不到一个用方法语法来说明这种情况的例子。我试图解决这个问题的方式当然可能是错误的,这就是为什么我找不到合适的例子。
我在这里找到了类似的东西,但无法在LinQPad中使用它: Is multiple .Where() statements in LINQ a performance issue?
或者这个,解决方案再次出现在查询语法中: Cross Join with Where clause
Albahari的这个例子:(http://www.linqpad.net/WhyLINQBeatsSQL.aspx)
from p in db.Purchases
where p.Customer.Address.State == "WA" || p.Customer == null
where p.PurchaseItems.Sum (pi => pi.SaleAmount) > 1000
select p
答案 0 :(得分:1)
考虑这个问题:
var q = from order in orders
from orderline in order.Lines
where orderline.Count > 10
select order.Discount * orderline.Price;
这或多或少对应
var q = orders
.SelectMany(order => order.Lines, (order, orderline) => new { order, orderline})
.Where(item => item.orderline.Count > 10)
.Select(item => item.order.Discount * item.orderline.Price);
有关SelectMany
的详细信息,请参阅the MSDN documentation。
如果您没有定义关联:
var q = from order in orders
from orderline in orderLines
where orderline.OrderId == order.Id
where orderline.Count > 10
select order.Discount * orderline.Price;
这或多或少对应
var q = orders
.SelectMany(order => orderLines, (order, orderline) => new { order, orderline})
.Where(item => item.orderline.OrderId == item.order.Id)
.Where(item => item.orderline.Count > 10)
.Select(item => item.order.Discount * item.orderline.Price);