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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.