Inject from ExpandoObject with ValueInjecter
Asked Answered
D

2

6

I'm using ValueInjecter for object mapping and I'm trying to inject from an ExpandoObject. I found an example of injecting from a dynamic.

   public class Ac
    {
        public string Aa { get; set; }
    }

    [Test]
    public void Aa()
    {
        var o = new { Aa = "aa" };
        dynamic d = o;
        var a = new Ac{ Aa = "bb" };
        a.InjectFrom((object)d);
        Assert.AreEqual(o.Aa, a.Aa);
    }

But I have not been successful in getting it to work with an ExpandoObject. How can I do this?

Duodecimal answered 29/7, 2011 at 22:10 Comment(1)
See this q for a more complete answer.Cannabis
L
8
using System;
using System.Collections.Generic;
using System.Dynamic;
using Omu.ValueInjecter;

namespace ConsoleApplication7
{
    public class FromExpando : KnownSourceValueInjection<ExpandoObject>
    {
        protected override void Inject(ExpandoObject source, object target)
        {
            var d = source as IDictionary<string, object>;
            if (d == null) return;
            var tprops = target.GetProps();

            foreach (var o in d)
            {
                var tp = tprops.GetByName(o.Key);
                if (tp == null) continue;
                tp.SetValue(target, o.Value);
            }
        }
    }

    public class Foo
    {
        public string Name { get; set; }
        public int Ace { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            dynamic x = new ExpandoObject();
            x.Ace = 1231;
            x.Name = "hi";
            var f = new Foo();
            //f.InjectFrom<FromExpando>((object) x); // edit:compilation error
            new FromExpando().Map((object)x,f);
            Console.WriteLine(f.Ace);
            Console.WriteLine(f.Name);
        }
    }
} 
Limonene answered 1/8, 2011 at 6:48 Comment(1)
@nawfal, have you found a solution to support nested types?Kalagher
V
1

I have used the same approach as Omu posted reading from a ExpandoObject that comes from a XML. As all the properties comes in as ´string´, so I have tweaked @Omu's answer a little using the ´Convert.ChangeType´ method:

public class FromExpando : KnownSourceValueInjection<ExpandoObject>
{
    protected override void Inject(ExpandoObject source, object target)
    {
        var d = source as IDictionary<string, object>;
        if (d == null) return;
        var tprops = target.GetProps();

        foreach (var o in d)
        {
            var tp = tprops.GetByName(o.Key);
            if (tp == null) continue;

            var newValue = Convert.ChangeType(o.Value, tp.PropertyType); 

            tp.SetValue(target, newValue);
        }
    }
}
Veneration answered 18/6, 2014 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.