© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
9 replies
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();
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.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

EF Core
C#CC# / help
2y ago
Ef core help
C#CC# / help
10mo ago
✅ EF Core Relationship
C#CC# / help
2y ago