2012-11-16 54 views
1

EDITED:我正在檢索一些訂單數據,並試圖從第一個表中使用productID從另一個表中獲取產品描述。下面的代碼工作正常,但我需要使用的productid得到的字符串來查詢產品表,產品說明linq使用兩個表的實體

Dim result = From c In ctx.orders 
         Where c.CustomerId = 13 
       Select New With 
       {c.OrderDate, 
       c.PurchaseOrderNumber, 
       c.ProductId, 
       c.ProductPrice, 
       c.ProductQty} 

我嘗試以下,並獲得建議「字段或屬性命名的productid犯規存在」錯誤 使用這種方法

Dim result = From c In ctx.orders 
         Where c.CustomerId = 13 
        Join prod In ctx.products on c.ProductId Equals prod.Id 
       Select New With 
       {c.OrderDate, 
       c.PurchaseOrderNumber, 
       prod.Description, 
       c.ProductPrice, 
       c.ProductQty} 

回答

0

爲什麼不使用join operator C# versionjoin operator VB version

Dim result = From c In ctx.orders 
      Join prod In ctx.products On c.ProductId Equals prod.Id 
      Where c.CustomerId = custid 
      Select New With 
        {c.OrderDate, 
         prod.Description 
        c.ProductPrice, 
        c.ProductQty} 

我做了一個SAMPL e類來測試連接,並且這個工作完美。你確定它裝載了產品表並且它有財產嗎?

Module Module1 

Sub Main() 
    Dim ctx As List(Of X) = New List(Of X) 
    Dim x1 As X = New X() 
    x1.One = 1 
    x1.Two = 2 
    Dim x2 As X = New X() 
    x2.One = 10 
    x2.Two = 20 
    ctx.Add(x1) 
    ctx.Add(x2) 

    Dim ctx2 As List(Of Y) = New List(Of Y) 
    Dim y1 As Y = New Y() 
    y1.Three = 1 
    y1.Four = 2 
    Dim y2 As Y = New Y() 
    y2.Three = 10 
    y2.Four = 20 
    ctx2.Add(y1) 
    ctx2.Add(y2) 

    Dim result = From c In ctx 
     Join prod In ctx2 On c.One Equals prod.Three 
     Where c.One = 1 
     Select New With 
       {c.One, 
       prod.Four, 
       c.Two} 

    For Each a In result 
     Console.Beep() 
    Next 

    Console.Read() 
End Sub 

Class X 
    Public Property One As Integer 
    Public Property Two As Integer 
End Class 

Class Y 
    Public Property Three As Integer 
    Public Property Four As Integer 
End Class 

End Module 
+0

VS不喜歡的 「進prodDesc」 的一部分。我改變了查詢有點removinf「進入prodDesc」和改變prodDesc.Description prod.Description和它errs說(「沒有產品ID存在),這顯然不是真的 – dinotom

+0

@dinotom嘗試更新的代碼。對不起,我在做一些C#的東西,它似乎有一些細微的差別。 –

+0

這類似於我是從原來的建議做什麼,我仍然得到同樣的錯誤「字段或已命名的productId所選數據未找到屬性,但它確實填充網格的第一列(它似乎barf上的prod.description) – dinotom

0

爲什麼不使用這樣的: 昏暗結果=從c在ctx.orders 。凡(C => c.CustomerId = 13) .SelectMany(C => c.products); 然後你會得到所有的產品在oders。