[英]How to get the reference to newly constructed instance in expression tree c#
是否可以在以下表達式樹中獲取對PositionViewModel
的引用:
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()
};
}
}
我認為是,因為EF做到了。 有什么建議么?
編輯:忘了提到“Postition”是ViewModel類型。
我會自發地分步進行:
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;
}
這樣你仍然可以將它作為表達式樹包裝起來。
您可以做的是使用Employees
屬性的事實,因此您可以將任何代碼添加到其setter中。 就像是:
private IList<Employee> employees;
public IList<Employee> Employees
{
get
{
return employees;
}
set
{
employees = value;
foreach (var employee in employees)
{
employee.Position = this;
}
}
}
這樣,您不需要在表達式中執行任何操作,並且將自動設置Position
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.