Convert SQL Query to Linq (contains left joins)

匆匆过客 提交于 2019-12-30 07:33:11

问题


I have a query that works perfectly in SQL, but I'm having the damnedest time converting it to linq. The table (Table1 below) holds status changes for multiple record types. The join requires two fields to be set to create the valid join: A SubmissionId (pk of the table the status pertains to), and a SubmissionTypeId (determines what table the status pertains to).

CREATE TABLE ##Table1 (Id int, Status varchar(50), SubmissionId int, SubmissionTypeId int)
insert into ##Table1(Id, Status, SubmissionId, SubmissionTypeId)
select 1 ,'Status1' ,1 , 1    
union select 2,'Status2',1, 2

CREATE TABLE ##Table2 (ID int, Value varchar(50))
insert into ##Table2 (ID, Value)
select 1, 'Value1Table2'

CREATE TABLE ##Table3 (ID int, Value varchar(50))
insert into ##Table3 (ID, Value)
select 1, 'Value1Table3'

select ds.* from ##Table1 ds
left join ##Table2 di
on ds.SubmissionId = di.Id and ds.SubmissionTypeId = 2
left join ##Table2 dr
on ds.SubmissionId = dr.Id and ds.SubmissionTypeId = 1
where SubmissionTypeId in (1,2)

I've tried a couple of iterations using the into x from y in x.DefaultIfEmpty() and I can't set the where clause in the right location. I need to start the query with Table1 since that is where the values are coming from.

As a work around I split the query into two parts and just added the status data sequentially to a list, but it seems there must be a better way.

Thank you.


回答1:


I think a direct translation of your SQL would look like this:

var q = from ds in table1
        where ds.SubmissionTypeId == 1 || ds.SubmissionTypeId == 2
        from di in table2
        from dr in table2
        where (ds.SubmissionTypeId == 2 && ds.SubmissionId == di.Id)
           || (ds.SubmissionTypeId == 1 && ds.SubmissionId == dr.Id)
        select ds;

However, it seems unlikely that this is what you want. If I may speculate about what your intended logic is, I think you want something more like this:

var q = from ds in table1
        where (ds.SubmissionTypeId == 2 && table2.Any(di => ds.SubmissionId == di.Id))
           || (ds.SubmissionTypeId == 1 && table3.Any(dr => ds.SubmissionId == dr.Id))
        select ds;


来源:https://stackoverflow.com/questions/4696616/convert-sql-query-to-linq-contains-left-joins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!