我问一个问题早了解为什么左连接Linq中不能使用定义的关系 ;到目前为止我还没有得到令人满意的响应。

现在,在平行的轨道,我已经接受了我需要的,如果没有我的对象之间的关系定义为使用join关键字,而我试图找出如何表达我的Linq查询。麻烦的是,它的左边的聚集多个表之间的连接,与参与加入多个领域。有没有这种简化的方法,所以这里的一切暴露无遗荣耀的SQL:

select *
from TreatmentPlan tp
join TreatmentPlanDetail tpd on tpd.TreatmentPlanID = tp.ID
join TreatmentAuthorization auth on auth.TreatmentPlanDetailID = tpd.ID
left join PatientServicePrescription rx on tpd.ServiceTypeID = rx.ServiceTypeID
left join PayerServiceTypeRules pstr on auth.PayerID = pstr.PayerID and tpd.ServiceTypeID = pstr.ServiceTypeID and pstr.RequiresPrescription = 1
where tp.PatientID = @PatientID

(仅供参考,如果它有助于理解我想要做的事:我想,以确定是否有此TreatmentPlanDetail在授权Patient需要这个Payer处方任何ServiceType记录,但要么没有ServicePerscription记录,或者它已过期。)

现在,这里是我的C#代码如下所示:

var q = from tp in TreatmentPlans
        from tpd in tp.Details
        from auth in tpd.Authorizations
        join rx in ServicePrescriptions.DefaultIfEmpty() on tpd.ServiceTypeID equals rx.ServiceTypeID
        // from pstr in auth.Payer.ServiceTypeRules.DefaultIfEmpty() -- very frustrating that this doesn't work!!
        join pstr in LinqUtils.GetTable<PayerServiceTypeRules>().DefaultIfEmpty()
        on new { auth.PayerID, tpd.ServiceTypeID, RxReq = (bool)true } equals new { pstr.PayerID, pstr.ServiceTypeID, pstr.RequiresPrescription }
        select new { Payer = auth.Payer, Prescription = rx, TreatmentPlanDetail = tpd, Rules = pstr };

哎呀,不编译!出于某种原因(我喜欢的解释)我不能使用文字布尔等值连接里面!好吧,我会离开它,并筛选出了“RequiresPrescription”的东西后...

...
join pstr in LinqUtils.GetTable<PayerServiceTypeRules>().DefaultIfEmpty()
on new { auth.PayerID, tpd.ServiceTypeID } equals new { pstr.PayerID, pstr.ServiceTypeID }
...

...现在它编译 - 但是当我跑,我得到一个“对象未设置”例外在这条线上。 DUH!当然还有空在那里!否则怎么是你应该执行与左一个比较加盟,如果你不能引用右侧的对象,这可能潜在地为空?

那么,如何是你应该做的左使用连接多个字段?

有帮助吗?

解决方案

我认为你需要使用into关键字和解决失踪儿童的DefaultIfEmpty()的之后的联接,而不是之前:

...
join pstr in LinqUtils.GetTable<PayerServiceTypeRules>()
on new { auth.PayerID, tpd.ServiceTypeID, bool RequiresPrescription = true } 
equals new { pstr.PayerID, pstr.ServiceTypeID, pstr.RequiresPrescription } 
into pstrs
from PSTR in pstrs.DefaultIfEmpty()
select new { 
    Payer = auth.Payer, 
    Prescription = rx, 
    TreatmentPlanDetail = tpd, 
    Rules = PSTR 
};

LinqUtils.GetTable<PayerServiceTypeRules>().DefaultIfEmpty()可能是转向了空,因为 DataTable中返回不包含任何行的,从而导致你的异常。注意在整个语句后in会选择到它,这是不是你想要的行为之前执行。如果不存在匹配的行,你想匹配的行或空。


有关布尔问题,它是一个命名问题(无“RxReq”匹配在右侧并没有什么左侧“RequiresPrescription”匹配)。尝试命名true“RequiresPrescription”我有上述(或命名右侧的pstr.RequiresPrescription“RxReq”)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top