NHibernate Linq 的 join (聯合查詢) 的例子
阿新 • • 發佈:2019-02-02
1. 如果一個表中的id為非空而另一個表的id為可空 如何連結
var q =
from o in db.Orders
join e in db.Employees
on o.Employee.EmployeeId equals (int?) e.EmployeeId into emps
from e in emps
select new {o.OrderId, e.FirstName};
2. 用where連線
var q =
from e1 in db.Employees
from e2 in e1.Subordinates
where e1.Address.City == e2.Address.City
select new
{
FirstName1 = e1.FirstName,
LastName1 = e1.LastName,
FirstName2 = e2.FirstName,
LastName2 = e2.LastName,
e1.Address.City
};
3.用join後的結果統計
var q =
from c in db.Customers
join o in db.Orders on c.CustomerId equals o.Customer.CustomerId into orders
select new {c.ContactName, OrderCount = orders.Average(x => x.Freight)};
var q =
from c in db.Customers
join o in db.Orders on c.CustomerId equals o.Customer.CustomerId into ords
join e in db.Employees on c.Address.City equals e.Address.City into emps
select new {c.ContactName, ords = ords.Count(), emps = emps.Count() };
4.group join
var q = from c in db.Customers
join o in db.Orders on c.CustomerId equals o.Customer.CustomerId
group new { c, o } by c.ContactName
into g
select new { ContactName = g.Key, OrderCount = g.Average(i => i.o.Freight) };
var q =
from o in db.Orders
join e in db.Employees
on o.Employee.EmployeeId equals (int?) e.EmployeeId into emps
from e in emps
select new {o.OrderId, e.FirstName};
2. 用where連線
var q =
from e1 in db.Employees
from e2 in e1.Subordinates
where e1.Address.City == e2.Address.City
select new
{
FirstName1 = e1.FirstName,
LastName1 = e1.LastName,
FirstName2 = e2.FirstName,
LastName2 = e2.LastName,
e1.Address.City
};
3.用join後的結果統計
var q =
from c in db.Customers
join o in db.Orders on c.CustomerId equals o.Customer.CustomerId into orders
select new {c.ContactName, OrderCount = orders.Average(x => x.Freight)};
var q =
from c in db.Customers
join o in db.Orders on c.CustomerId equals o.Customer.CustomerId into ords
join e in db.Employees on c.Address.City equals e.Address.City into emps
select new {c.ContactName, ords = ords.Count(), emps = emps.Count()
4.group join
var q = from c in db.Customers
join o in db.Orders on c.CustomerId equals o.Customer.CustomerId
group new { c, o } by c.ContactName
into g
select new { ContactName = g.Key, OrderCount = g.Average(i => i.o.Freight) };