1

我是 LINQ 和 Lamda 表达式的新手。我有一个有点复杂的 SQL 语句,它从几个数据库表中检索信息:

SELECT A.OrderID, A.FORMJDENO, A.Title, B.Descr, C.Code, C.Descr, D.ModificationDate from OrderForm A 
LEFT JOIN OrderPriority B ON A.OrderPriorityID = B.OrderPriorityID 
LEFT JOIN StockClass C ON A.StockClassID = C.StockClassID 
LEFT JOIN AuditTrailLog D ON A.OrderID = D.ObjectID 
WHERE D.ColumnInfoID= 487 AND D.OldValue='1' AND D.NewValue='2' AND A.FormStatus=2 AND A.FormType=3 AND B.OrderPriorityID=1000001 AND C.StockClassID=1000002
AND A.DeptID IN 
    ( SELECT DeptID FROM Department WHERE InstID = 1000006 )
AND DATEDIFF(m,D.ModificationDate, A.VendorDeliveryDate) >= 3   

我已经几乎完成了 LINQ,使用.Contains()替换WHERE...INSQL 子句的方法,但我需要一些帮助来joins根据属于其他表的值限制结果并DATEDIFF在 LINQ 中使用等效项。这是我已经得到的并且工作正常,但显然它并没有像上面的 SQL 语句那样限制结果。我尝试了几种方法都没有成功。我需要等效的 LINQ

更新:

最后我能够让它工作。这是检索与 SQL 语句相同的记录的最终 LINQ。非常感谢@Gert Arnold:

var valid = dba.OrderForm
            .Where(q => q.FormType == 3
                        && q.FormStatus == 2
                        && q.OrderPriority.OrderPriorityID == orderpriorityID
                        && q.StockClass.StockClassID == stockclassID
                        && dba.AuditTrailLog.Where(log => q.OrderID==log.ObjectID)
                                .Any(log => log.ColumnInfoID == 487
                                            &&  log.OldValue == "1"
                                            && log.NewValue == "2"
                                            && EntityFunctions.DiffMonths(log.ModificationDate,     
                                                                 q.VendorDeliveryDate) >= period)
                        && departments.Contains(q.DeptID));
4

1 回答 1

3

我认为这是关于它的:

dba.OrderForm.Where(q => q.FormType == 3 
    && q.FormStatus == 2   
    && q.OrderPriority.OrderPriorityID == 1000001
    && q.StockClass.StockClassID == 1000002
    && q.AuditTrailLogs
        .Any(log => log.ColumnInfoID == 487
                 && log.OldValue == "1"
                 && log.NewValue == "2"
                 && EntityFunctions.DiffMonths(log.ModificationDate, 
                                                 q.VendorDeliveryDate) >= 3)
    && departments.Contains(q.DeptID));

我假设您已经(或可以创建)一个导航属性OrderTable.AuditTrailLogs

没有导航属性,您可以使用

&& dba.AuditTrailLogs.Where(log => q.OrderID == log.ObjectID).Any(...
于 2013-05-09T13:23:16.233 回答