Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

What you could do is to use the fact that Employees is a property, so you can add any code you want to its setter. Something like:

private IList<Employee> employees;

public IList<Employee> Employees
{
    get
    {
        return employees;
    }

    set
    {
        employees = value;

        foreach (var employee in employees)
        {
            employee.Position = this;
        }
    }
}

With this, you don't need to do anything in your expression, and the Position will be set automatically.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top