1

我在数据库中有三个表,它们对应于我们代码中的实体。(为简单起见,我正在简化这些类)

public class Current{
    [Key]
    public int CurrentId {get; set;}

    [Required]
    public int TableKeyId {get; set;}

    public string Value {get; set;}
}

public class Promotion{
    [Key]
    public int PromtionId {get; set;}

    [Required]
    public int TableKeyId {get; set;}

    public string Value {get; set;}
}

public class TableKey{
    [Key]
    public int TableKeyId {get;set;}

    [Required]
    public string PlanCode {get;set;}

    [Required]
    public byte Environment {get;set;}

    [Required]
    public byte FileId {get;set;}

    [Required]
    public string TableNumber {get;set;}

}

(Current 和 Promotion 都具有 TableKeyId 外键属性)。

我需要做的是从所有三个存储库中提取获取它们的值和 TableKey 属性的 Currents 和 Promotions。我需要所有的 Promotions(如果它们存在)以及它们的 TableKeyId 不等于 Promotions 中的任何 TableKeyId 的 Currents。我尝试使用以下查询来完成此操作:

var query = (from c in this.currentRepository.Query()
                     join t in this.tableKeyRepository.All() on c.TableKeyId equals t.TableKeyId
                     join p in this.promotionRepository.Query() on c.TableKeyId equals p.TableKeyId into pc
                     from p in pc.DefaultIfEmpty()
                     where (t.PlanCode == command.PlanCode && t.Environment == command.Environment)
                     select new Temptable
                     {
                         TableNumber = t.TableNumber,
                         PlanCode = t.PlanCode,
                         FileId = t.FileId,
                         Value = (p == null ? c.Value : p.Value),
                         TableKeyId = c.TableKeyId
                     });

此查询几乎可以工作,除非存在具有 TableKeyId 的 Promotion 与具有相同 TableKeyId 的 Current 不对应的 Promotion - 它不会检索那些,因为它是左外连接。我知道我可以用多个查询来做到这一点,但我真的想要一个查询。还要记住,每个表可能有大约 100 万条记录,所以我必须优化查询。

因此,如果我有以下内容:

表键

TableKeyId,PlanCode,Environment,FileId,TableNumber
--------------------------------------------------
1,"001",2,"PFT","A1234"
2,"001",2,"PFT","A1235"
3,"001",2,"PFT","A1236"
4,"001",2,"PFT","A1237"

电流

CurrentId,TableKeyId,Value
--------------------------
1,1,"A"
2,2,"B"
3,4,"C"

促销活动

PromotionId,TableKeyId,Value
---------------------------
1,1,"G"
2,2,"H"
3,3,"I"

如果 Environment 是 2 并且 PlanCode 在我的查询中是“001”,我希望结果集是

TableKeyId,PlanCode,Environment,FileId,TableNumber,Value
--------------------------------------------------------
1,"001",2,"PFT","A1234","G"
2,"001",2,"PFT","A1235","H"
3,"001",2,"PFT","A1236","I"
4,"001",2,"PFT","A1237","C"

我非常感谢所有反馈:)

谢谢!

4

0 回答 0