我在db中有三个表,对应于代码中的实体。 (为简单起见,我将这些课程搞砸了)
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外键属性)。
我需要做的是从所有三个存储库中取出检索Currents和Promotions获取它们的值和TableKey属性。 我需要所有促销活动(如果它们存在)以及其TableKeyId与促销活动中的任何TableKeyId不相等的电流。我尝试使用以下查询完成此操作:
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的Current不对应的TableKeyId的Promotion,否则它将不会检索它们,因为它是左外连接。我知道我可以使用多个查询来完成它,但我真的想要一个查询。另外请记住,每个表可能有大约1百万条记录,所以我必须优化查询。
所以,如果我有以下内容:
TableKeys
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"
如果我的查询中环境为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"
我非常感谢所有反馈:)
谢谢!