2

我的应用程序中有一个 Entity Framework 4 模型。我需要它来生成以下 SQL:

SELECT *
FROM       Reads            AS R
INNER JOIN Images           AS I ON R.ReadId = I.ReadId AND I.ImageTypeId = 2
LEFT OUTER JOIN Alarms      AS A ON R.ReadId = A.ReadId AND A.DomainId IN (103,102,101,2,1,12) AND A.i_active = 1
LEFT OUTER JOIN ListDetails AS L ON L.ListDetailId = A.ListDetailId
WHERE R.i_active = 1

这是我现在在我的代码中对此查询的内容:

var items = from read  in query
            join plate in context.Images      on read.ReadId        equals plate.ReadId
            join temp1 in context.Alarms      on read.ReadId        equals temp1.ReadId       into alarms  from alarm in  alarms.DefaultIfEmpty()
            join temp2 in context.ListDetails on alarm.ListDetailId equals temp2.ListDetailId into entries from entry in entries.DefaultIfEmpty()
            where plate.ImageTypeId == 2 && plate.IActive == 1
            select new { read, plate, alarm, entry.OfficerNotes };

如何修改实体框架查询以获得我需要的 SQL 查询?

4

1 回答 1

2

对于左连接 - 我建议使用 afromwhere不是join,我发现它更干净

对于具有多个连接条件的内部连接 ​​- 您需要连接两个匹配的匿名类型,或使用fromwithwhere条件

对于 x IN 列表,您需要在查询之外指定您的列表并使用Any方法或Contains方法

List<int> domainIds = new List<int>() { 103,102,101,2,1,12 };

    var items = from read  in query
                join plate in context.Images
                on new { read.ReadId, ImageTypeId = 2 } equals new { plate.ReadId, plate.ImageTypeId }
                from alarm in context.Alarms
                                     .Where(x => x.IActive == 1)
                                     .Where(x => domainIds.Any(y => y == x.DomainId))
                                     .Where(x => read.ReadId == x.ReadId)
                                     .DefaultIfEmpty()
                from entry in context.ListDetails 
                                     .Where(x => alarm.ListDetailId == x.ListDetailId)
                                     .DefaultIfEmpty()
                select new { read, plate, alarm, entry.OfficerNotes };
于 2012-07-20T14:38:27.277 回答