将三个查询组合成一个外部联接

时间:2016-09-30 14:04:07

标签: c# entity-framework linq

目前我有三个这样的查询:

var query1 = (from a in dbContext.Table1 
              where a.email == someEmail 
              select a.Table1K).ToList();
var query2 = (from a in dbContext.Table2 
              where a.emailAddrerss == someEmail 
              select a.Table2K).ToList();
var query3 = (from a in dbContext.Table3 
              where a.email == someEmail 
              select a.Table3K).ToList();

if ( query2.Any() || query3.Any() )
{
   return false;
}

if(query1.Count == 1 )
{
   var x = query1[0];
   // do some stuff with that x value ... 
}

有没有办法用外连接(我对外连接不是很好)我们可以在一个查询而不是三个查询中实现这个?

1 个答案:

答案 0 :(得分:1)

我不认为实际的加入是合适的,但你确实有一些改进的机会:

  • 如果您只是想检查任何结果,请不要在查询2或3上调用ToList
  • 如果您只想从查询1中获取一个结果,请改为呼叫SingleOrDefault

    var query1 = (from a in dbContext.Table1 
                  where a.email == someEmail 
                  select a.Table1K);
    var query2 = (from a in dbContext.Table2 
                  where a.emailAddrerss == someEmail 
                  select a.Table2K);
    var query3 = (from a in dbContext.Table3 
                  where a.email == someEmail 
                  select a.Table3K);
    
    
    if ( query2.Any() || query3.Any() )
    {
       return false;
    }
    
    var x = query1.SingleOrDefault();
    if(x != null)
    {
       // do some stuff with that x value ... 
    }