In Entity Framework Core 2.1, we can use query types , as suggested by Yuri N.
A more detailed article on how to use them can be found here.
. The simplest approach in accordance with the examples from the article:
1. We have, for example, the following entity models for publishing management
public class Magazine { public int MagazineId { get; set; } public string Name { get; set; } public string Publisher { get; set; } public List<Article> Articles { get; set; } } public class Article { public int ArticleId { get; set; } public string Title { get; set; } public int MagazineId { get; set; } public DateTime PublishDate { get; set; } public Author Author { get; set; } public int AuthorId { get; set; } } public class Author { public int AuthorId { get; set; } public string Name { get; set; } public List<Article> Articles { get; set; } }
2. We have a view called AuthorArticleCounts defined to return the title and number of articles written by the author
SELECT a.AuthorName, Count(r.ArticleId) as ArticleCount from Authors a JOIN Articles r on r.AuthorId = a.AuthorId GROUP BY a.AuthorName
3. We go and create a model that will be used for the view
public class AuthorArticleCount { public string AuthorName { get; private set; } public int ArticleCount { get; private set; } }
4. After that, we create the DbQuery property in my DbContext to use the view results inside the model.
public DbQuery<AuthorArticleCount> AuthorArticleCounts{get;set;}
5. Finally, we can easily get the viewing results as follows.
var results=_context.AuthorArticleCounts.ToList();
UPDATE According to the comment
It is worth noting that DbQuery will no longer / is not supported in EF Core 3.0
Anastasios selmanis
source share