© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
3 replies
Thinker

Turn recursive entities into model [Answered]

I have two db entities like this:
public sealed class TodoListEntity {
  public Guid Id { get; set; }
  public ICollection<TodoItemEntity> Items { get; set; } = null!;
}
public sealed class TodoListEntity {
  public Guid Id { get; set; }
  public ICollection<TodoItemEntity> Items { get; set; } = null!;
}
public sealed class TodoItemEntity {
  public Guid Id { get; set; }
  // Other data

  public Guid ListId { get; set; }
  public TodoListEntity List { get; set; } = null!;
}
public sealed class TodoItemEntity {
  public Guid Id { get; set; }
  // Other data

  public Guid ListId { get; set; }
  public TodoListEntity List { get; set; } = null!;
}

I wanna turn this into a model/DTO, so I have these extensions
public static TodoList ToModel(this TodoListEntity entity) =>
  new(entity.Id, entity.Items.Select(ToModel).ToArray());
public static TodoItem ToModel(this TodoItemEntity entity) =>
  new(entity.Id, /* Other data */, entity.List.ToModel());
public static TodoList ToModel(this TodoListEntity entity) =>
  new(entity.Id, entity.Items.Select(ToModel).ToArray());
public static TodoItem ToModel(this TodoItemEntity entity) =>
  new(entity.Id, /* Other data */, entity.List.ToModel());

This however causes a stack overflow because
ToModel(TodoListEntity)
ToModel(TodoListEntity)
calls
ToModel(TodoItemEntity)
ToModel(TodoItemEntity)
and so on which causes unbound recursion. What would the simplest way to fix this be? I somehow have to keep a single list which I can pass to all items inside it.
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

Iterative from Recursive [Answered]
C#CC# / help
4y ago
CSharp Code into Class [Answered]
C#CC# / help
4y ago
EF Core not fetching sub-entities by Id [Answered]
C#CC# / help
4y ago
Query over multiple entities using the same interface [Answered]
C#CC# / help
4y ago