使用C#表达式树,我能创建一个匿名到类型化对象映射吗?

4

这个问题涉及到数据层,因此性能非常重要。否则我会使用Automapper。如果它是IDBConnection,我将使用Dapper。

我想将匿名对象的简单编写转化为POCO并使用编译表达式来表达它。

代码

public class Foo
{
    public string Bar{get;set;}
    public string Baz{get;set;}
}

public void doStuff()
{
     var obj = new{Bar= "My Name, Baz = "Some other data"};

     //can I recreate this assignment to foo using expressions?
     var foo = new Foo{
         Bar = obj.Bar,
         Baz = obj.Baz
     }
}

(未完整) 到目前为止,我已经...

var props = o.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)

    foreach (var prop in props)
                {
                    var targetProp = typeof(T).GetProperty(prop.Name);
                    var targetExp = Expression.Parameter(typeof(T), "target");
                    var valueExp = Expression.Parameter(prop.PropertyType, "property");



                    var propExp = Expression.Property(targetExp, targetProp);
                    var assignExp = Expression.Assign(propExp, valueExp);

                    var setter = Expression.Lambda<Action<T, object>>(assignExp, targetExp, valueExp).Compile();
                }

目前存在的问题

  1. 如何将setter组合成一个返回编译后委托的方法?
  2. 当我遍历属性时,如何创建Lambda[Action]泛型类型?

感谢任何和所有的帮助。


顺便提一下,找出类似这样的东西最简单的方法就是编写一个编译为表达式树的 lambda 表达式,然后反编译它。 - Jon Skeet
我会的。我只是没有提到那部分。重复使用它没有问题...问题在于创建它。 - BlackjacketMack
好的,让我在那里提供更完整的图片。 - BlackjacketMack
使用List<>对象将会有所帮助。public class Foo { public string Bar{get;set;} public string Baz{get;set;} public List<Foo> children {get;set;} } - jdweng
1
一定要尝试使用FastMapper/Mapster。它们会生成动态IL来映射对象,因此性能比Automapper高一个数量级。 - Wiktor Zychla
显示剩余4条评论
1个回答

7

这里是你需要的翻译:

using System;
using System.Linq;
using System.Linq.Expressions;

namespace Tests
{
    public static class Utils
    {
        public static Func<TInput, TOutput> CreateMapFunc<TInput, TOutput>()
        {
            var source = Expression.Parameter(typeof(TInput), "source");
            var body = Expression.MemberInit(Expression.New(typeof(TOutput)),
                source.Type.GetProperties().Select(p => Expression.Bind(typeof(TOutput).GetProperty(p.Name), Expression.Property(source, p))));
            var expr = Expression.Lambda<Func<TInput, TOutput>>(body, source);
            return expr.Compile();
        }
    }
    public static class MapFunc<TInput, TOutput>
    {
        public static readonly Func<TInput, TOutput> Instance = Utils.CreateMapFunc<TInput, TOutput>();
    }
    public struct Unit<T>
    {
        public readonly T Value;
        public Unit(T value) { Value = value; }
        public U MapTo<U>() { return MapFunc<T, U>.Instance(Value); }
    }
    public static class Extensions
    {
        public static Unit<T> Unit<T>(this T source) { return new Unit<T>(source); }
    }
    // Test
    public class Foo
    {
        public string Bar { get; set; }
        public string Baz { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var obj = new { Bar = "My Name", Baz = "Some other data" };
            //var foo = new Foo { Bar = obj.Bar, Baz = obj.Baz };
            var foo = obj.Unit().MapTo<Foo>();
        }
    }
}

如果有人对它是如何工作感兴趣:
主要部分是CreateMapFunc函数,通过使用MemberInitExpression构建和编译lambda表达式。 它确实应该是MapFunc<TInput,TOutput>类中的私有函数 - 我将其放在了一个单独的类中,只是为了展示原始问题的答案。 MapFunc<TInput,TOutput>类是单例并充当编译函数委托的缓存。 Unit<T>充当中介者(与扩展方法一起使用),需要允许推断传递的匿名对象类型并仅指定目标类型。

不错!这正是我所期望的用法。 - BlackjacketMack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接