Entity Framework Core Use Include on QueryType(Database View)

.net c# entity-framework entity-framework-core


I have EF Core connected to MySql and I have a View called:


I read this article saying I can use Query Types for Database Views.

It works if I just call _context.PostViews, but if I use Include on it like:

_context.PostViews.Include(xxxx), it throws me this error:

System.InvalidOperationException: 'The property 'Comment' is not a navigation property of entity type 'PostWithViews'. The 'Include(string)' method can only be used with a '.' separated list of navigation property names.'

enter image description here

PostView has all properties in Post (id, title, content, Comment etc.), plus it has one extra column called: Views which shows how many people have read this post.

Here is my Post:

public partial class Post
        public Post()
            Comment = new HashSet<Comment>();

        public string Id { get; set; }
        public string ApartmentId { get; set; }
        public string AuthorId { get; set; }
        public string CategoryId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime? DueDate { get; set; }
        public bool? Disabled { get; set; }
        public DateTime? CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
        public string UpdatedBy { get; set; }

        public virtual Apartment Apartment { get; set; }
        public virtual User Author { get; set; }
        public virtual PostCategory Category { get; set; }}
        public virtual ICollection<Comment> Comment { get; set; }

PostWithViews class is almost the same with Post but with 1 more property Views:

public int Views { get; set; }

Here is how I include properties e.g. Comment :

return GetAll()
       .Include(p => p.Author)
       .Include(p => p.Comment)
5/15/2019 7:29:41 PM

Popular Answer

Currently (EF Core 2.x) query types do not support collection navigation properties, as mentioned in the Compare query types to entity types documentation topic:

  • They can only contain reference navigation properties pointing to entities.

So although your Comment property looks like collection navigation property, for EF Core it s isn't, hence cannot be used in Include / ThenInclude (or LINQ to Entities query).

However Apartment, Author and Category are "reference navigation properties pointing to entities", so they should be fully functional.

5/15/2019 7:27:56 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow