I'm trying to find a way to filter my results in EF Core 2.1, when using inherited objects.
I've got a base model and several inherited classes (but I've just included one):
public class Like {
public int Id { get; set; }
public LikeType LikeType { get; set; }
}
public class DocumentLike : Like {
[ForeignKey(nameof(Document))]
public int DocumentId { get; set; }
public virtual Document Document { get; set; }
}
LikeType is an enum which is defined as the discriminator in the dbcontext. Every Document has a boolean property .IsCurrent.
To get all items from the database, I'm using a query like:
IQueryable<Like> query = _context.Set<Like>()
.Include(x => x.Owner)
.Include(x => (x as DocumentLike).Document.DocumentType)
.Include(x => (x as ProductLike).Product)
.Include(x => (x as TrainingLike).Training)
This works beautifully, and returns all objects with the included sub-objects without any error. What I'm trying to do, is to get all items from the database for which the linked document has .IsCurrent == true. I've tried adding the following to the query above, but both result in an exception:
.Where(x => (x as DocumentLike).Document.IsCurrent == true)
And:
.Where(x => x.LikeType == LikeType.Document ? (x as DocumentLike).Document.IsCurrent == true : true)
The exception, which is thrown when I'm executing the query:
NullReferenceException: Object reference not set to an instance of an object.
lambda_method(Closure , TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<Like, ApplicationUser>, Organisation>, Training>, Product>, Platform>, NewsItem>, Event>, Document>, DocumentType>, Course>, CourseType>, ApplicationUser> )
System.Linq.Utilities+<>c__DisplayClass1_0<TSource>.<CombinePredicates>b__0(TSource x)
System.Linq.Enumerable+WhereSelectEnumerableIterator<TSource, TResult>.MoveNext()
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities<TOut, TIn>(IEnumerable<TOut> results, QueryContext queryContext, IList<EntityTrackingInfo> entityTrackingInfos, IList<Func<TIn, object>> entityAccessors)+MoveNext()
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider+ExceptionInterceptor<T>+EnumeratorExceptionInterceptor.MoveNext()
System.Collections.Generic.List<T>.AddEnumerable(IEnumerable<T> enumerable)
System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source)
Is there a way to do this?
UPDATE:
To clarify: I'm looking to get a single query that returns all Like-objects from the database, regardless of their (sub)types. In case the subtype is DocumentLike, I only want the objects that are linked to a document that has .IsCurrent == true.