Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用ValueInjector控制去扁深度_C#_Asp.net Mvc 4_Valueinjecter - Fatal编程技术网

C# 如何使用ValueInjector控制去扁深度

C# 如何使用ValueInjector控制去扁深度,c#,asp.net-mvc-4,valueinjecter,C#,Asp.net Mvc 4,Valueinjecter,我确信这个解决方案是显而易见的,但是关于如何使用ValueInjector完成以下工作,我有什么想法吗 假设您有以下型号: 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;} } 视图模

我确信这个解决方案是显而易见的,但是关于如何使用ValueInjector完成以下工作,我有什么想法吗

假设您有以下型号:

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;}
}
在对Foo对象调用InjectFrom时,我只希望填充Foo.BarId属性,而不是Foo.Bar.Id属性。如果在图中较浅的深度处发现与属性名称完全匹配的对象,我希望尽可能阻止取消平台过程在整个对象图中递归


理想情况下,我希望这样做,而不必显式忽略属性,也不必按照惯例这样做。

在深入了解源代码之后,答案是,我怀疑实现起来微不足道

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中的逻辑深入到对象图中