我有兩個表,表 A(loan_id,金額)和表 B(id,loan_id)。現在我想從表 A 中選擇表 B 中沒有貸款 ID 的行。例如
Table A has following rows:
loan_id amount
------- ------
1 200
2 400
Table B has following rows:
id loan_id
-- -------
1 2
在上面的場景中,我想根據loan_id加入這個表并只顯示那些在表B中不可用的行。我希望輸出應該如下所示
output:
loan_id amount
------- ------
1 200
我怎樣才能使用物體框架實作這一點。到目前為止,我知道我需要執行左連接并選擇那些 B.id == null 的行,但是,我沒有找到如何使用 c#、linq 執行此操作。
編輯:
在這里我還添加了我的物體類:
[Table("loans")] ( in my given scenario this is table A)
public class Loan
{
[Column("loan_id")]
public int Id { get; set; }
[Column("funding_amount")]
public decimal FundingAmount { get; set; }
}
[Table("loan_approves")] (in my given scenario this is table B)
public class LoanApprove
{
[Column("id")]
public int Id { get; set; }
[Column("loan_id")]
public int LoanId { get; set; }
}
uj5u.com熱心網友回復:
您的查詢應如下所示:
var result = context.Loan
.Where(l => !context.LoanApprove.Any(a => a.LoanId == l.Id))
.ToList();
或與 NOT IN
var result = context.Loan
.Where(l => !context.LoanApprove.Select(a => a.LoanId).Contains(l.Id))
.ToList();
uj5u.com熱心網友回復:
由于您尚未提供有關物體類外觀的任何詳細資訊,這只是一個猜測:
假設你有:
class TableA
{
public int LoanId { get; set; }
public decimal Amount { get; set; }
public List<TableB> TableBs { get; set; }
}
class TableB
{
public int Id { get; set; }
public int LoanId { get; set; }
public TableA Loan { get; set; }
}
然后你只需要使用:
var result = context.TableAs.Where(a => !a.TableBs.Any()).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/363366.html
下一篇:通過擴展方法過濾子查詢
