I use Entity Framework Core 2.0 and have this 2 classes:
News
public class News
{
public int Id { get; s
Instead of using an anonymous object, you can return from your infra layer a method IQueryable
and just do an context.NewsTable.Include(x => x.Author)
.
Obs: Note that you're just returning a query and not retrieving data from your DB at this point.
Then you create a NewsDTO
class with the properties you want to retrieve (example bellow).
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; }
}
I prefer to use AutoMapper, your code will be cleaner, List
But you can do using this odd kind
List newsDtoList = _repository.GetAll()
.Select(x => new NewsDTO
{
Id = x.Id.,
Title = x.Title,
Text = x.Text,
ReleaseDate = x.ReleaseDate,
AuthorName = x.Author.Username
}).ToList();
You finish your command using .ToList()
, at this point you retrieve your data, just one select with the fields you defined in your mapping configuration or in your select.