C#C
C#2y ago
Haeri

EF Core Nested Projections

I am trying to find out a good way to perform a projection on a model with multiple relationship levels. Here is an example:

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Other { get; set; }
    public User User { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public int Other { get; set; }
}

public class BlogDTO
{
    public int Id { get; set; }
    public string Title { get; set; }
    public UserDTO User { get; set; }
}

public class UserDTO
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

var result = dbContext.Blogs
    .Select(blog => new BlogDTO
    {
        Id = blog.Id,
        Title = blog.Title,
        User = new UserDTO
        {
            Id = blog.User.Id,
            UserName = blog.User.UserName
        }
    })
    .toList();


This works but I have a lot more levels in my code and writing this out every time is super tedious. I'l looking for a way to reuse the projections so I don't have to write them out every time.
Was this page helpful?