【问题标题】:Linq IEnumerable to entity cast errorLinq IEnumerable 到实体转换错误
【发布时间】:2015-04-30 18:52:33
【问题描述】:

请参考我下面的代码。返回值发生异常错误。 无法将“System.Data.Objects.ObjectQuery1[VB$AnonymousType_23[System.String,System.String,System.String]]”类型的对象转换为“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

我在选择部分尝试了以下方法,但错误结果相同

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

非常感谢任何帮助。

【问题讨论】:

    标签: vb.net linq


    【解决方案1】:

    如果您想返回 List(Of stk_cust),您需要创建 stk_cust 的实例,而不是使用匿名类型。假设这些是属性:

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

    也许您也可以直接选择对象而无需创建新对象:

    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()
    

    【讨论】:

    • 谢谢蒂姆。我会尝试您的建议并回复您。
    • 嗨,蒂姆,在使用您的第一个建议进行测试后,我收到一个错误,“无法在 LINQ to Entities 查询中构造实体或复杂类型 'TotalModel.stk_cust'”。对于您的第二个选项,查询返回正确,但我无法获得与 s_armaster 相关的“名称”。
    猜你喜欢
    • 2012-07-26
    • 1970-01-01
    • 2013-05-03
    • 2012-09-13
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多