2012-11-21 111 views
2

我对LINQ非常陌生,我做了很多不成功的尝试将SQL查询转换为LINQ ..请帮我解决一些问题。什么是确切的LINQ for this ..谢谢提前。将sql查询转换为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 
+0

对于大查询,通常是在EF中创建存储过程或视图和地址的更好选择。特别是当“NOLOCK”的特定语法非常重要时,甚至不能使用linq。 –

+0

查看我的回答 –

回答

1

首先你的一部分,都需要重写查询更多的规范形式,你其实并不需要加入

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}; 
+0

非常感谢Roman,未来会遵循Ur指令,并且除了少数我能够管理的修改之外,给出的查询符合要求。问候.. –

+0

如果您觉得它有用,您能接受答案吗? –