2014-10-07 167 views
0

我有這個疑問:SQL查詢與聯接到Linq查詢

SELECT DISTINCT 
    responseInstanceID 
FROM 
    rRuleTriggerResponse rtr 
LEFT JOIN 
    rRuleTrigger rt ON rtr.ruleTriggerID = rt.ruleTriggerID 
LEFT JOIN 
    rRule r ON rt.ruleTriggerID = r.ruleTriggerID 
WHERE 
    r.ratingLogicVersion = '<<RatingLogicVersion>>' // RatingLogicVersion - e.g. "4.8" 

我需要將其轉換到LINQ查詢(C#)(獲得布爾值,如果responseInstanceID存在)

在C#我有這個結構:

public partial class rResponseInstance : BaseEntity 
    { 
     public rResponseInstance() 
     { 
      this.rRuleTriggerResponses = new List<rRuleTriggerResponse>(); 
     } 

     [Key("rResponseInstance", true)] 
     public int responseInstanceID { get; set; } 
     [Key("rQuestionInstance")] 
     public int questionInstanceID { get; set; } 
     public virtual ICollection<rRuleTriggerResponse> rRuleTriggerResponses { get; set; } 
    } 

public partial class rRuleTriggerResponse : BaseEntity 
    { 
     [Key("rRuleTriggerResponse", true)] 
     public int ruleTriggerResponseID { get; set; } 
     [Key("rRuleTrigger")] 
     public int ruleTriggerID { get; set; } 
     [Key("rResponseInstance")] 
     public int responseInstanceID { get; set; } 
     public virtual rResponseInstance rResponseInstance { get; set; } 
     public virtual rRuleTrigger rRuleTrigger { get; set; } 
    } 

public partial class rRuleTrigger : BaseEntity 
    { 
     public rRuleTrigger() 
     { 
      this.rRules = new List<rRule>(); 
      this.rRuleTriggerResponses = new List<rRuleTriggerResponse>(); 
     } 

     [Key("rRuleTrigger", true)] 
     public int ruleTriggerID { get; set; } 
     public virtual ICollection<rRule> rRules { get; set; } 
     public virtual ICollection<rRuleTriggerResponse> rRuleTriggerResponses { get; set; } 
    } 

public partial class rRule : BaseEntity 
    { 
     [Key("rRule", true)] 
     public int ruleID { get; set; } 
     [Key("rRatingLogic")] 
     public string ratingLogicVersion { get; set; } 
     [Key("rRuleTrigger")] 
     public int ruleTriggerID { get; set; } 
     public virtual rRatingLogic rRatingLogic { get; set; } 
     public virtual rRuleTrigger rRuleTrigger { get; set; } 
    } 

對於查詢,我只有一個對象 - rResponseInstance model。那麼,是否有可能只用型號執行SQL查詢?我很厲害的LINQ加入(

回答

0

不要使用join子句的一切,讓導航性能做的工作:

var ratingLogicVersion = "4.8"; 

var query = 
    db.rRuleTriggerResponses 
    .Where(resp => resp.rRuleTrigger.rRules 
         .Any(rule => ruler.ratingLogicVersion == ratingLogicVersion)) 
    .Select(resp => resp.responseInstanceID); 

注意,你不需要任何Distinct更多,因爲結果乘以結果不見了(取而代之的是EXISTS)。

+0

是的,我只是想這個。謝謝 – demo 2014-10-07 11:28:14