3

我正在更新一个旧应用程序,以使用 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; }
}

谁能帮我完成这个查询?

谢谢,

标记

4

2 回答 2

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对象的对象上的导航属性的正确引用。

于 2013-03-12T14:16:35.613 回答
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...*/ );

您可以将这些语句堆叠在一行中,我只是为了便于阅读而将它们分开 :)

于 2013-03-12T15:01:22.777 回答