Linq继承和子类型(想要过滤掉基类型)

时间:2010-11-08 14:47:41

标签: vb.net linq entity-framework linq-to-entities

好的我有一个返回列表的基本查询(ObjectQuery,实际上但我觉得不重要)

我有大约5种基于主要类型的子类型,我需要过滤它们。一切正常,直到我想要 结果是主要类型(不是子类)

基本上我有一个包含所有内容的查询,然后我过滤掉了在复选框列表中未选中的类型。 (asp.net)

假设我有一个名为Task的实体,以及从Task继承的SubTask1和SubTask2

       Dim AllTasks As Objects.ObjectQuery(Of Demo.Task) = dbContext.CompletedTasks(ctx, anyID)  'calling a compiled query but it doesnt matter. 
    'It could be Dim AllTasks = from t in ctx.Tasks select t

    For Each itm As ListItem In chkTaskTypeList.Items
        If Not itm.Selected Then
            Select Case itm.Value
                Case "SubTask1"
                    'this works as expected, and eliminates tasks that are of the subtype Subtask1 
                    AllTasks = From ti In AllTasks Where Not TypeOf ti Is SubTask1

                Case "SubTask2"
                    'This also works as I want by filtering out the various sub types
                    AllTasks = From ti In AllTasks Where Not TypeOf ti Is SubTask2 AndAlso Not TypeOf ti Is SubTaskWhatever

                Case "SubTask"
                    **'This works as expected, but not like I need. It removes all the types when what I really want is to remove** 
                    **'The results that are of the base type but NOT the ones that are of a subtype**
                    AllTasks = From ti In AllTasks Where Not TypeOf ti Is SubTask

            End Select
        End If
    Next

    lvwHistory.DataSource = AllTasks

如果我有一定数量的子类型,我可能会说(Not TypeOf ti Is SubTask andalso TypeOf ti is SubTask1),而且...... 但我希望有一个更好的方法(并且如果添加了新的子类型,则不会破坏页面)

2 个答案:

答案 0 :(得分:0)

您应该比较类型是否相等

OnlyBaseClasses = From ti In AllTasks Where ti.GetType() = GetType(TheBaseClass)

答案 1 :(得分:0)

这是difficult, but possible。但是,您应该重新考虑您的设计。这样做通常违反Liskov替代原则。