ASP.Net MVC将Sql转换为Linq

时间:2013-03-12 13:49:20

标签: linq entity-framework

我正在更新旧应用,使用EF和Linq。我遇到了其中一个查询的问题 - 在SQL中它是:

SELECT    id, type_id, rule_name, rule_start, rule_end, rule_min
FROM      Rules
WHERE     (rule_min > 0) 
          AND (rule_active = 1) 
          AND (rule_fri = 1) 
          AND ('2012-01-01' BETWEEN rule_start AND rule_end) 
          AND (id IN
                      (SELECT      rule_id
                        FROM       RulesApply
                        WHERE      (type_id = 3059)))
ORDER BY pri

到目前为止,我有:

         var rules = db.Rules.Include("RulesApply")
                .Where(t => (t.rule_active == 1)
                    && (t.rule_min > 0)
                    && (dteFrom >= t.rule_start && dteFrom <= t.rule_end)
                    && (this is where I'm stuck)
                    )
                    .OrderBy(r => r.pri);

这是我在上面的LINQ中添加的最后一个子查询:

AND (id IN
(SELECT      rule_id
FROM       RulesApply
WHERE      (type_id = 3059)))

模型是:

public class Rule
{
    [Key]
    public Int64 id { get; set; }
    public Int64 hotel_id { get; set; }
    public byte rule_active { get; set; }
    public DateTime rule_start { get; set; }
    public DateTime rule_end { get; set; }
    public int rule_min { get; set; }
    public int pri { get; set; }
    public virtual ICollection<RuleApply> RulesApply { get; set; }
}

public class RuleApply
{

    [Key, Column(Order = 0)]
    public Int64 type_id { get; set; }
    [Key, Column(Order = 1)]
    public Int64 rule_id { get; set; }
    [ForeignKey("rule_id")]
    public virtual Rule Rule { get; set; }
}

有人可以帮我完成这个查询吗?

谢谢,

标记

2 个答案:

答案 0 :(得分:2)

尝试这样做:

var rules = db.Rules.Include("RulesApply")
                .Where(t => (t.rule_active == 1)
                    && (t.rule_min > 0)
                    && (dteFrom >= t.rule_start && dteFrom <= t.rule_end)
                    && t.RulesApply.Any(a => a.type_id == 3059)
                    .OrderBy(r => r.pri);

如果t.RulesApply是非法的(即不编译),则将其替换为对Rules对象上指向RulesApply对象的导航属性的正确引用。

答案 1 :(得分:2)

如果您在实体之间设置了导航属性,则可以从一个实体导航到另一个:

//This gets the RulesApply object
var rulesapply = db.RulesApply.Single(x=> x.type_id == 3059);

//This gets all Rules connected to the rulesapply object through its navigational property
var rules = rulesapply.Rules;

//You can use LINQ to further refine what you want
rules = rules.Where( x=> /* and so on...*/ );

您可以将这些语句一起堆叠在一行中,我只是为了可读性而将它们拆分:)