将sql查询转换为linq查询

将sql查询转换为linq查询,linq,sql-to-linq-conversion,Linq,Sql To Linq Conversion,我对LINQ非常陌生,我曾多次尝试将SQL查询转换为LINQ,但都没有成功。。请帮我找出一些解决办法。具体的LINQ是多少。。提前谢谢 //只是整个查询的一部分 select distinct p.IdPatient,p.IdDoc from patd p (NOLOCK) left outer join StatusChange sc (NOLOCK) on sc.IdPatient = p.IdPatient and sc.IdClin

我对LINQ非常陌生,我曾多次尝试将SQL查询转换为LINQ,但都没有成功。。请帮我找出一些解决办法。具体的LINQ是多少。。提前谢谢

//只是整个查询的一部分

  select distinct p.IdPatient,p.IdDoc
  from patd p (NOLOCK)
     left outer join StatusChange sc (NOLOCK)
        on sc.IdPatient = p.IdPatient
           and sc.IdClinicNumber = 23430 
           and sc.IdStatus = 'A'
           and sc.DateStatusChange > GetDate()
     join TrtTyp t ON p.IdTreatmentType = t.IdTreatmentType 
           and t.TypeModality IN ('H','P')
  Where 
      p.IdType IN ('P','E','M')
      and (IsNull(p.IsInactive,0) in (1,0) or sc.IdStatusChange is not null)
      and Not Exists(
         Select 1
         From   Expire e (NOLOCK)
         Where  e.IdPatient = p.IdPatient
      )
      and p.IdClinicNumber = 23430

首先,您需要以更规范的形式重写查询,实际上不需要连接

select distinct
    p.IdPatient, p.IdDoc
from patd as p
where 
    p.IdClinicNumber = 23430 and
    p.IdType in ('P','E','M') and
    p.IdTreatmentType in
    (
         select tt.IdTreatmentType
         from TrtTyp as tt
         where tt.TypeModality in ('H','P')
    ) and
    (
        isnull(p.IsInactive, 0) in (1,0) or
        p.IdPatient in 
        (
            select sc.IdPatient
            from StatusChange as sc
            where
                sc.IdClinicNumber = p.IdClinicNumber and
                sc.IdStatus = 'A' and
                sc.DateStatusChange > GetDate()
        )
    ) and
    p.IdPatient not in
    (
        select e.IdPatient
        from expire as e
    )
现在你可以写你的LINQ了。请记住,我没有你的数据来测试它

var query = 
from p in patds
where
    p.IdClinicNumber == 23430 &&
    (new char[] { 'P', 'E', 'M' }).Contains(p.IdType) &&
    (
        from t in TrtTyps
        where (new char[] { 'H','P' }).Contains(t.TypeModality)
        select t.IdTreatmentType
    ).Contains(p.IdTreatmentType) &&
    (
        (new int[] { 1, 0 }).Contains(p.IsInactive ?? 0) ||
        (
            from sc in StatusChanges
            where
                sc.IdClinicNumber == p.IdClinicNumber &&
                sc.IdStatus == 'A' &&
                sc.DateStatusChange > DateTime.Now
            select sc.IdPatient
        ).Contains(p.IdPatient)
    ) &&
    !(
        from e in Expires
        select e.IdPatient
    ).Contains(p.IdPatient)
select new {p.IdPatient, p.IdDoc};

对于大的查询,在EF中创建存储过程或视图和地址通常是更好的选择。特别是当特定语法如
NOLOCK
非常重要时,您甚至不能使用linq。多亏了Roman,我们将在将来遵循您的指示,并且给出的查询符合要求,除了我能够管理的少量修改。当做