这可能更干净(你不需要所有的into
陈述):
var query = from order in dc.Orders from vendor in dc.Vendors .Where(v => v.Id == order.VendorId) .DefaultIfEmpty() from status in dc.Status .Where(s => s.Id == order.StatusId) .DefaultIfEmpty() select new { Order = order, Vendor = vendor, Status = status } //Vendor and Status properties will be null if the left join is null
这是另一个左连接示例
var results = from expense in expenseDataContext.ExpenseDtos where expense.Id == expenseId //some expense id that was passed in from category // left join on categories table if exists in expenseDataContext.CategoryDtos .Where(c => c.Id == expense.CategoryId) .DefaultIfEmpty() // left join on expense type table if exists from expenseType in expenseDataContext.ExpenseTypeDtos .Where(e => e.Id == expense.ExpenseTypeId) .DefaultIfEmpty() // left join on currency table if exists from currency in expenseDataContext.CurrencyDtos .Where(c => c.CurrencyID == expense.FKCurrencyID) .DefaultIfEmpty() select new { Expense = expense, // category will be null if join doesn't exist Category = category, // expensetype will be null if join doesn't exist ExpenseType = expenseType, // currency will be null if join doesn't exist Currency = currency }
无法访问VisualStudio(我在Mac上),但使用http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to中的信息-sql.aspx看起来你可能会做这样的事情:
var query = from o in dc.Orders join v in dc.Vendors on o.VendorId equals v.Id into ov from x in ov.DefaultIfEmpty() join s in dc.Status on o.StatusId equals s.Id into os from y in os.DefaultIfEmpty() select new { o.OrderNumber, x.VendorName, y.StatusName }
我想出了如何使用LINQ to SQL在VB.NET中使用多个左外连接:
Dim db As New ContractDataContext() Dim query = From o In db.Orders _ Group Join v In db.Vendors _ On v.VendorNumber Equals o.VendorNumber _ Into ov = Group _ From x In ov.DefaultIfEmpty() _ Group Join s In db.Status _ On s.Id Equals o.StatusId Into os = Group _ From y In os.DefaultIfEmpty() _ Where o.OrderNumber >= 100000 And o.OrderNumber <= 200000 _ Select Vendor_Name = x.Name, _ Order_Number = o.OrderNumber, _ Status_Name = y.StatusName
在VB.NET中使用Function,
Dim query = From order In dc.Orders From vendor In dc.Vendors.Where(Function(v) v.Id = order.VendorId).DefaultIfEmpty() From status In dc.Status.Where(Function(s) s.Id = order.StatusId).DefaultIfEmpty() Select Order = order, Vendor = vendor, Status = status