Select specific properties from the entities included in the kernel

I am using Entity Framework Core 2.0 and have this 2 classes:

news

public class News
{
    public int Id { get; set; }
    public string Title{ get; set; }
    public string Text { get; set; }
    public DateTime ReleaseDate{ get; set; }
    public int AuthorID{ get; set; }
    public Author Author{ get; set; }
}

Author

public class Author 
{
    public Author ()
    {
     News = new List<News>();
    }

    public int Id { get; set; }
    public string Username{ get; set; }
    public string Firstname{ get; set; }
    public string Lastname{ get; set; }
    public ICollection<News> News {get;set;}
}

I want to download the news with the author’s username only because I do not need other information, such as the author’s name and name.

If I do this:

static void Main(string[] args)
{
  using (var ctx = new DbContext())
  {
   var result= ctx.News.Include(x => x.Author).Select(news => new
   {
     news= news ,
     Username= pr.Author.Username
   }).ToList();
  }
}

Entity Framework Core 2.0 generates a database query, for example:

SELECT [x].[ID], [x].[Text], [x].[Title], [x].[AuthorId], [x].[ReleaseDate], [x.Author].[ID], [x.Verfasser].[Username] AS [Username], [x.Verfasser].[Firstname], [x.Verfasser].[Lastname]
FROM [News] AS [x]
INNER JOIN [Author] AS [x.Author] ON [x].[AuthorId] = [x.Author].[ID]

Is there a way to achieve the expected behavior?

+5
source share
2 answers

If I understand correctly, you do not want to load the object Author(because there is no way to load the object with some non-adaptive navigation properties enabled).

, Include(x => x.Author), EF Author. Include/ThenInclude . , (Select).

, EF (Core) EFC 2.0 , . EFC , Ignored Includes. , , EFC 2.0 ! , , .

Include . :

var result = ctx.News.Select(news => new
{
    news = news,
    Username = news.Author.Username
}).ToList();

SQL- EFC , :

SELECT [news].[Id], [news].[AuthorID], [news].[ReleaseDate], [news].[Text], [news].[Title], [news.Author].[Username]
FROM [News] AS [news]
INNER JOIN [Authors] AS [news.Author] ON [news].[AuthorID] = [news.Author].[Id] 
+9

, IQueryable<News> GetAll() IQueryable<News> GetAll() context.NewsTable.Include(x => x.Author). Obs: , , .

NewsDTO , ( ).

public class NewsDTO
{
    public int Id { get; set; }
    public string Title{ get; set; }
    public string Text { get; set; }
    public DateTime ReleaseDate{ get; set; }
    public string AuthorName { get; set; }
}

AutoMapper, , List<NewsDTO> newsDtoList = _repository.GetAll().ProjectTo<NewsDTO>().ToList()

,

List<NewsDTO> newsDtoList = _repository.GetAll()
.Select(x => new NewsDTO
        {
            Id = x.Id.,
            Title = x.Title,
            Text = x.Text,
            ReleaseDate = x.ReleaseDate,
            AuthorName = x.Author.Username
        }).ToList();

, .ToList(), , , .

0

Source: https://habr.com/ru/post/1686576/


All Articles