【问题标题】:Convert IEnumerable to EntityCollection Entity Framework 4将 IEnumerable 转换为 EntityCollection 实体框架 4
【发布时间】:2010-02-16 15:30:22
【问题描述】:

我使用 Entity Framework 4 为导航属性生成了以下代码:

<XmlIgnoreAttribute()>
<SoapIgnoreAttribute()>
<DataMemberAttribute()>
<EdmRelationshipNavigationPropertyAttribute("Diagnose", "Request_Comments", "Comment")>
Public Property Comments() As EntityCollection(Of Comment)
    Get
        Return CType(Me,IEntityWithRelationships).RelationshipManager.GetRelatedCollection(Of Comment)("Diagnose.Request_Comments", "Comment")
    End Get
    Set
        If (Not value Is Nothing)
            CType(Me, IEntityWithRelationships).RelationshipManager.InitializeRelatedCollection(Of Comment)("Diagnose.Request_Comments", "Comment", value)
        End If
    End Set
End Property

当我想通过像这样添加 WHERE 子句来减少 GET 的结果时

Return CType(Me,IEntityWithRelationships).RelationshipManager.GetRelatedCollection(Of Comment)("Diagnose.Request_Comments", "Comment") _
.Where(Function(p) p.IsDeleted = False)

或使用 Linq

Return From x In CType(Me,IEntityWithRelationships).RelationshipManager.GetRelatedCollection(Of Comment)("Diagnose.Request_Comments", "Comment") _
Where x.IsDeleted = False Select x

运行应用程序时抛出以下异常:

Unable to cast object of type 'WhereEnumerableIterator`1[DAL.Comment]' to type 'System.Data.Objects.DataClasses.EntityCollection`1[DAL.Comment]'.

我不知道如何将结果(我认为是 IEnumerable)从查询转换为 EntityCollection。我尝试添加一个“.ToList”,但没有帮助。
有谁知道该问题的解决方案或从集合中剔除已删除项目的更好方法?

【问题讨论】:

    标签: .net entity-framework collections ienumerable


    【解决方案1】:

    你真的需要它成为一个 EntityCollection 吗? 您可以创建一个新的只读属性,如下所示:

    Public ReadOnly Property ActiveComments() As IEnumerable(Of Comment)
        Get
           Return From x In CType(Me,IEntityWithRelationships).RelationshipManager.GetRelatedCollection(Of Comment)("Diagnose.Request_Comments", "Comment") _
    Where x.IsDeleted = False Select x
        End Get
    End Property
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多