Linq Inheritance and subtypes (want to filter out base type)
OK I have a base query that is returning a list (ObjectQuery, actually but I don't think it matters)
I have about 5 subtypes based on the main type and I need to filter them. Everything works fine until I want the results to be of the main type (not a subclass)
Basically I have a query that includes everything, then I filter out the types that are not checked in a checkedbox list. (asp.net)
Lets say I have an Entity named Task, and SubTask1 and SubTask2 that inherit from Task
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 开发者_如何学GoIn 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
If I had a limted number of subtypes I could probably say something like (Not TypeOf ti Is SubTask andalso TypeOf ti Is SubTask1) andalso ... but I am hoping for a better way (and one which doesn't break the page if a new subtype added)
You should compare if the types are equal
OnlyBaseClasses = From ti In AllTasks Where ti.GetType() = GetType(TheBaseClass)
This is difficult, but possible. However, you should rethink your design. Doing this usually violates the Liskov Substitution Principle.
精彩评论