简体   繁体   English

如何在表达式树c#中获取对新构造实例的引用

[英]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: 是否可以在以下表达式树中获取对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()
            };
        }
    }

I think it is, because EF does that. 我认为是,因为EF做到了。 Any suggestions? 有什么建议么?

Edit: Forgot to mention that "Postition" is of type ViewModel. 编辑:忘了提到“Postition”是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. 您可以做的是使用Employees属性的事实,因此您可以将任何代码添加到其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. 这样,您不需要在表达式中执行任何操作,并且将自动设置Position

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM