如何使用ValueInjecter控制不平整的深度

时间:2013-07-23 16:10:24

标签: c# asp.net-mvc-4 valueinjecter

我确定这个解决方案非常明显,但有关我如何使用值injecter执行以下操作的任何想法?

假设您有以下型号:

public class Foo{
    public int BarId{get;set;}
    public Bar Bar{get;set;}
}

public class Bar{
    public int Id{get;set;}
    [Required]
    public string Description{get;set;}
}

和一个看起来像这样的视图模型:

public class FooBarViewModel{
    public int BarId{get;set;}
    public bool EditMode{get;set;}
}

当我在InjectFrom<UnflatLoopValueInjection>()对象上调用Foo时,我只希望填充Foo.BarId属性,而不是Foo.Bar.Id属性。如果在图中较浅的深度找到与属性名称完全匹配的话,我想尽可能地停止Unflattening过程在整个对象图中的递归。

理想情况下,我希望这样做,而不是通过明确忽略属性并按惯例执行此操作。

1 个答案:

答案 0 :(得分:0)

我已经深入挖掘了一些答案,因为我怀疑实施起来很简单

public class UnflatLoopValueInjectionUseExactMatchIfPresent : UnflatLoopValueInjection {
    protected override void Inject(object source, object target) {
        var targetProperties = target.GetProps().Cast<PropertyDescriptor>().AsQueryable();
        foreach (PropertyDescriptor sourceProp in source.GetProps()) {
            var prop = sourceProp;
            if (targetProperties.Any(p => p.Name == prop.Name)) {
                //Exact match found
                targetProperties.First(p => p.Name == prop.Name).SetValue(target, SetValue(sourceProp.GetValue(source)));
            }
            else {
                //Fall back to UnflatLoopValueInjection
                var endpoints = UberFlatter.Unflat(sourceProp.Name, target, t => TypesMatch(prop.PropertyType, t)).ToList();
                if (!endpoints.Any()) {
                    continue;
                }
                var value = sourceProp.GetValue(source);
                if (!AllowSetValue(value)) {
                    continue;
                }
                foreach (var endpoint in endpoints) {
                    endpoint.Property.SetValue(endpoint.Component, SetValue(value));
                }
            }
        }
    }
}

如果未找到viewmodels属性名称的完全匹配,则上述注入将仅深入深入(使用标准UnflatLoopValueInjection中的逻辑)到对象图中。