Search code examples
c#lambdaexpression-treesprojection

How to get the reference to newly constructed instance in expression tree c#


Is It possible to get the reference to the PositionViewModel in the following expression tree:

    public static Expression<Func<Model, ViewModel>> ToViewModel
    {
        get
        {
            return x => new PositionViewModel
            {
                Id = x.Id,
                Name = x.Name,
                Employees = x.Employees.Select(e => new Employee
                {
                    Id = e.Id,
                    Name = e.Name,
                    Position = ??? // reference to PositionViewModel
                }).ToList()
            };
        }
    }

I think it is, because EF does that. Any suggestions?

Edit: Forgot to mention that "Postition" is of type ViewModel.


Solution

  • I would spontaneously do it in steps:

    public static Expression<Func<Model, ViewModel>> ToViewModel
    {
        get
        {
            return x => GetViewModel(x);
        }
    }
    
    public ViewModel GetViewModel(Model x)
    {
        var vm = new PositionViewModel
        {
            Id = x.Id,
            Name = x.Name
        };
    
        vm.Employees = x.Employees.Select(p => new Employee
        {
            Id = p.Id,
            Name = p.Name,
            Position = vm
        }).ToList();
    
        return vm;
    }
    

    This way you can still wrap this up as an expression tree.