I have a Category Entity that has a collection of child Categories and a nullable reference to a Parent Category.
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public Category Parent { get; set; }
public ICollection<Category> Children { get; set; }
}
I have the scenario where I need to "copy" an existing entity (Zone) which has references to Categories. Within the select statement I need to map the existing categories and their children to a new Category record so that when I save the new categories will hold a reference to the new copied Zone.
The problem I'm having is a recursion method that will loop through the current LINQ select (x) Category and create new Category records for each of its children s children etc.
Here is the relevant part of the current "copy" select statement I have. Do I call Where on Categories that are top level i.e don't have a ParentId and then use a recursive method for the children?
Categories = zone.Categories.Where(y => !y.ParentId.HasValue).Select(x => new Category
{
Children = WHAT DO I PUT IN HERE
Name = x.Name,
}).ToList()