将IEnumerable转换为EntityCollection实体框架4

时间:2010-02-16 15:30:22

标签: .net entity-framework collections ienumerable

我使用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-Clause来减少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”,但这没有帮助 有没有人知道该问题的解决方案或更好的方法从集合中删除已删除的项目?

1 个答案:

答案 0 :(得分:0)

你真的需要它成为一个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