将复杂查询转换为linq

时间:2017-08-08 10:34:20

标签: linq entity

我正在尝试使用以下查询与Entity框架,这就是我尝试使用linq的原因。

SELECT DISTINCT
  elt.Type,
  ( SELECT TOP 1 Value
    from ELD
    where ELDTID = 2 AND ELID = el.ELID
  ) ID,
  ( SELECT TOP 1 Value
    from ELD
    Where ELDTID = 1 AND ELID = el.ELID
  ) Company,
  ( SELECT TOP 1 Value
    from ELD
    Where ELDTID = 5 AND ELID = el.EventLogID
  ) Message,
  ( SELECT Max(ET)
    FROM EL el
    INNER JOIN ELD eld ON eld.ELID = el.ELTID
    WHERE el.ELID = el.ELID
  ) ET
FROM EL el
INNER JOIN ITS.ELT elt ON elt.ELTID = el.ELTID
WHERE ELSID = 3

2 个答案:

答案 0 :(得分:1)

试试这个,可能是你需要的

    (from el in _context.EL.Where(p=>p.ELSID == 3)
    join elt from _context.ELT on elt.ELTID equals el.ELTID
    let ID = el.ELD.Where(p=>p.ELDTID == 2 ).Select(p=>p.Value).FirstOrDefault()
    let Company = el.ELD.Where(p=>p.ELDTID == 1 ).Select(p=>p.Value).FirstOrDefault()
    let Message = el.ELD.Where(p=>p.ELDTID == 5 && p.ELID = el.EventLogID).Select(p=>p.Value).Max()
    let ET = el.Select(p=>p.ET).MAX()
    select new
    {
        elt.Type,
        ID,
        Company,
        Message,
        ET
    }).ToList();

答案 1 :(得分:1)

  • 从示例中看不出ELSID是EL还是ELT属性,假设是ELT。

  • 我认为你的ET子查询中发现了一个错误:where el.ELID = el.ELID。您可能希望在一侧引用外部查询中的el,但不能因为您使用相同的名称。在子答案EL的答案中使用了el1。

尝试创建匹配的数据模型(下次请为我们提供一个,因为您可能已经拥有它)。

public class Elt
{
    public int ELTID;
    public int ELSID;
    public int Type;
}

public class El
{
    public int ELID;
    public int ELTID;
    public int EventLogID;
}

public class Eld
{
    public int ELDTID;
    public int ELID;
    public int ET;
    public int Value;
}

public class Db
{
    public IQueryable<El> Els;
    public IQueryable<Elt> Elts;
    public IQueryable<Eld> Elds;
}

您的SQL应该对应于此查询:

from el in db.Els
join elt in db.Elts on el.ELTID equals elt.ELTID
where elt.ELSID == 3
select new
{
    elt.Type,
    ID = (from eld in db.Elds where eld.ELDTID == 2 && eld.ELID == el.ELID select eld.Value).FirstOrDefault(),
    Company = (from eld in db.Elds where eld.ELDTID == 1 && eld.ELID == el.ELID select eld.Value).FirstOrDefault(),
    Message = (from eld in db.Elds where eld.ELDTID == 5 && eld.ELID == el.EventLogID select eld.Value).FirstOrDefault(),
    ET = (
        from el1 in db.Els
        join eld in db.Elds on el1.ELTID equals eld.ELDTID
        where el1.ELID == el.ELID
        select eld)
        .Max(eld => eld.ET),
};

如果您没有导航属性(ELT上EL的子集合,EL上ELD的子集合,EL和ELD上的父属性)我建议您添加它们,这将进一步简化查询(连接条件) EF注入:

from elt in db.Elts
from el in elt.Els
...