Wilson Teo
Wilson Teo

Reputation: 83

Linq IEnumerable to entity cast error

Please refer to my following code. An exception error occurs at the return value. Unable to cast object of type 'System.Data.Objects.ObjectQuery1[VB$AnonymousType_23[System.String,System.String,System.String]]' to type 'System.Collections.Generic.List`1[MyEntities.stk_cust]'.

Public Function GetCustomerProdListToGrid() As List(Of stk_cust)
        Dim result = From s In Db.stk_cust
             Group Join d In Db.s_armaster On d.dbcode Equals s.dbcode Into stk_ar = Group
             From d In stk_ar.DefaultIfEmpty()
             Order By s.stk_code, s.dbcode Ascending
             Select s.stk_code, s.dbcode, d.name
   Return result 
 End Function

I've tried the following method at select section but error turns out the same

Select New With {.stk_code = s.stk_code,
        .dbcode = s.dbcode,
        .name = d.name
  }

Any help is highly appreciated.

Upvotes: 1

Views: 476

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460288

If you want to return a List(Of stk_cust) you need to create instances of stk_cust instead of using an anonymous type. Presuming that those are the properties:

....
Select New stk_cust() With {
      .stk_code = s.stk_code,
      .dbcode = s.dbcode,
      .name = d.name
}

Return result.ToList()

Maybe you could also select the object directly without needing to create a new one:

Dim result = From s In Db.stk_cust
             Group Join d In Db.s_armaster On d.dbcode Equals s.dbcode Into stk_ar = Group
             From d In stk_ar.DefaultIfEmpty()
             Order By s.stk_code, s.dbcode Ascending
             Select s
Return result.ToList()

Upvotes: 1

Related Questions