问题
I have EF Core connected to MySql and I have a View called:
PostViews
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.'
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)
回答1:
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.
回答2:
an include function needs a query parameter but it still does not know its object so you need to use a lambda function to pass its object and the parameter you want
try it: _context.PostView.Include(lambda => lambda.Comment);
来源:https://stackoverflow.com/questions/56137189/entity-framework-core-use-include-on-querytypedatabase-view