gpt4 book ai didi

vb.net - Linq 到 Sql : Multiple left outer joins

转载 作者:行者123 更新时间:2023-12-03 04:19:39 35 4
gpt4 key购买 nike

我在弄清楚如何使用 LINQ to SQL 使用多个左外连接时遇到了一些麻烦。我了解如何使用一个左外连接。我正在使用VB.NET。下面是我的 SQL 语法。

T-SQL

SELECT
o.OrderNumber,
v.VendorName,
s.StatusName
FROM
Orders o
LEFT OUTER JOIN Vendors v ON
v.Id = o.VendorId
LEFT OUTER JOIN Status s ON
s.Id = o.StatusId
WHERE
o.OrderNumber >= 100000 AND
o.OrderNumber <= 200000

最佳答案

这可能更清晰(您不需要所有 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
}

关于vb.net - Linq 到 Sql : Multiple left outer joins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/267488/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com