linq - ASP.Net MVC 将 Sql 转换为 Linq

标签 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; }
}

谁能帮我完成这个查询?

谢谢,

标记

最佳答案

尝试这样做:

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 对象。

关于linq - ASP.Net MVC 将 Sql 转换为 Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15363031/

相关文章:

c# - 这个 LINQ 性能从何而来?

C# - LINQ - 对其他表中的字段求和

c# - 通过字符串更改属性的状态

c# - EF映射表错误 "Invalid column name XXX_Id"

c# - 如何在 C# 中旋转列表

c# - List<T> - 由 T.field 区分

c# - LINQ 按特定列返回不同值

c# - 设计师问题 + Entity Framework (WPF MVVM)

c# - 使用反射动态地将对象添加到 Entity Framework

c# - 将对象添加到实体集会创建不需要的新数据库行(多对多)。与现有对象建立关系?