如何在 Entity Framework 中的两个 table 之间进行左联接操作时 select 从左 table 开始的唯一行

How to select unique rows from left table while doing left join operation between two tables in Entity Framework

我有两个table,table A (loan_id, amount) 和table B (id, loan_id)。现在我想 table A 中的 select 行,其中 loan_id 在 table B 中不可用。例如

Table A has following rows:
loan_id   amount
-------   ------
1         200
2         400

Table B has following rows:
id     loan_id
--     -------
1      2

在上面的场景中,我想加入这个基于 loan_id 的 table 并且只显示那些在 table B 中不可用的行。我希望输出应该像正在关注

 output:
loan_id   amount
-------   ------
1         200

如何使用 Entity framework 实现此目的。到目前为止,我知道我需要执行左连接和 select 那些 B.id == null 的行,但是,我没有找到如何使用 c#、linq 执行此操作。

编辑:

这里我也添加了我的实体class:

[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; }
}

由于您没有提供您的实体 类 的任何详细信息,这只是一个猜测:

假设你有:

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();

您的查询应如下所示:

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();