2012-11-21 235 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

如果您覺得它有用,您能接受答案嗎? –