سؤال

Im sure the solution is blindingly obvious but any ideas on how i would do the following with value injecter?

Say you have the following model:

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;}
}

and a view model that looks like this:

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

when i call InjectFrom<UnflatLoopValueInjection>() on the Foo object i only want the Foo.BarId property populated, not the Foo.Bar.Id property as well. I would like to if possible stop the Unflattening process from recursing through the whole object graph if an exact match to a property name is found at a shallower depth in the graph.

Ideally i would like to do this without resorting to explicitly ignoring properties and being able to do this by convention.

هل كانت مفيدة؟

المحلول

Having dug into the source a bit more the answer was as i suspected trivial to implement

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));
                }
            }
        }
    }
}

The above injection will only drill down deeper (using the logic from the standard UnflatLoopValueInjection) into the object graph if an exact match for the viewmodels property name is not found.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top