2011-08-18 63 views
2

我需要這個SQL查詢轉換爲LINQ查詢,我也需要公開SQL選擇屬性:轉換這個SQL查詢來LINQ查詢

SELECT Problem.ProblemID, ProblemFactory.ObjectiveID, Objective.Name, ProblemFactory.Time, ProblemType.ProblemTypeName, ProblemFactory.OperationID, 
        ProblemFactory.Range1ID, ProblemFactory.Range2ID, ProblemFactory.Range3ID, ProblemFactory.Range4ID, 
        ProblemFactory.MissingNumber 
FROM Problem INNER JOIN ProblemFactory ON Problem.ProblemFactoryID = ProblemFactory.ProblemFactoryID 
      INNER JOIN ProblemType ON ProblemFactory.ProblemTypeID = ProblemType.ProblemTypeID 
      INNER JOIN Objective ON Objective.ObjectiveID = ProblemFactory.ObjectiveID 

更新1:

這是什麼我有:

 var query = from problem in dc.Problem2s 
        from factory 
        in dc.ProblemFactories 
         .Where(v => v.ProblemFactoryID == problem.ProblemFactoryID) 
         .DefaultIfEmpty() 
        from ... 

而且我用這個例子:What is the syntax for an inner join in LINQ to SQL?

+0

好的,那你的問題是什麼?我們不會爲你做你的工作... – cdhowie

+0

我知道,雖然這只是一個疑問。我沒有和LINQ一起工作得很好。我需要一點幫助。問題是我使用三個內部連接,我不知道如何在LINQ中轉換它 – Darf

+0

我更新了文章 – Darf

回答

3

像這樣的東西?

var query = 
    from p in ctx.Problem 
    join pf in ctx.ProblemFactory on p.ProblemFactoryID equals pf.ProblemFactoryID 
    join pt in ctx.ProblemType on pf.ProblemTypeID equals pt.ProblemTypeID 
    join o in ctx.Objective on pf.ObjectiveID equals o.ObjectiveID 
    select new 
    { 
     p.ProblemID, 
     pf.ObjectiveID, 
     o.Name, 
     pf.Time, 
     pt.ProblemTypeName, 
     pf.OperationID, 
     pf.Range1ID, 
     pf.Range2ID, 
     pf.Range3ID, 
     pf.Range4ID, 
     pf.MissingNumber, 
    }; 

但你是什麼意思的「SQL選擇屬性」?

+0

我認爲我在找什麼。我在我的數據庫中使用了存儲過程,但是我意識到我無法獲取屬性,因爲我使用了多個表。所以你在選擇新的方面做了什麼,你揭露了這些屬性,這就是我需要的。 – Darf

0

像Linq-to-SQL這樣的ORM的好處之一就是我們不必將我們的數據拼湊起來從數據庫中檢索它。如果您在設計師(即,如果你有他們的關係映射)映射你的對象,你應該能夠只獲得了​​,然後根據需要獲取相關的屬性...

var problems = from problem in dc.Problem2s select problem; 

foreach (var problem in problems) 
{ 
    // you can work with the problem, its objective, and its problem type. 
    problem.DoThings(); 
    var objective = problem.Objective; 
    var type = problem.ProblemType;  
} 

因此,你保留一個邏輯數據層中的數據結構,而不是無法輕易傳遞的匿名類型。

+0

明天我會測試一下。現在是午夜 – Darf