3

次のように、プロジェクションを使用してLINQで2つのオブジェクトタイプをマップできることを知っています。

var destModel = from m in sourceModel
               select new DestModelType {A = m.A, C = m.C, E = m.E}

どこ

class SourceModelType
{
    string A {get; set;}
    string B {get; set;}
    string C {get; set;}
    string D {get; set;}
    string E {get; set;}
}

class DestModelType
{
    string A {get; set;}
    string C {get; set;}
    string E {get; set;}
}

しかし、これを行うためにジェネリックのようなものを作りたい場合はどうなりますか?私が扱っている2つのタイプを具体的に知りません。したがって、「Dest」タイプをウォークし、一致する「Source」タイプと一致します。これは可能ですか?また、遅延実行を実現するには、IQueryableを返すだけにします。

例えば:

public IQueryable<TDest> ProjectionMap<TSource, TDest>(IQueryable<TSource> sourceModel)
{
   // dynamically build the LINQ projection based on the properties in TDest

   // return the IQueryable containing the constructed projection
}

これは難しいことですが、不可能ではないことを願っています。モデルとビューモデル間の明示的なマッピング作業を大幅に節約できるからです。

4

1 に答える 1

6

式ツリーを生成する必要がありますが、単純なものなので、それほど難しくはありません...

void Main()
{
    var source = new[]
    {
        new SourceModelType { A = "hello", B = "world", C = "foo", D = "bar", E = "Baz" },
        new SourceModelType { A = "The", B = "answer", C = "is", D = "42", E = "!" }
    };

    var dest = ProjectionMap<SourceModelType, DestModelType>(source.AsQueryable());
    dest.Dump();
}

public static IQueryable<TDest> ProjectionMap<TSource, TDest>(IQueryable<TSource> sourceModel)
    where TDest : new()
{
    var sourceProperties = typeof(TSource).GetProperties().Where(p => p.CanRead);
    var destProperties =   typeof(TDest).GetProperties().Where(p => p.CanWrite);
    var propertyMap = from d in destProperties
                      join s in sourceProperties on new { d.Name, d.PropertyType } equals new { s.Name, s.PropertyType }
                      select new { Source = s, Dest = d };
    var itemParam = Expression.Parameter(typeof(TSource), "item");
    var memberBindings = propertyMap.Select(p => (MemberBinding)Expression.Bind(p.Dest, Expression.Property(itemParam, p.Source)));
    var newExpression = Expression.New(typeof(TDest));
    var memberInitExpression = Expression.MemberInit(newExpression, memberBindings);
    var projection = Expression.Lambda<Func<TSource, TDest>>(memberInitExpression, itemParam);
    projection.Dump();
    return sourceModel.Select(projection);
}

(LinqPadでテストされているため、Dumps)

生成された射影式は次のようになります。

item => new DestModelType() {A = item.A, C = item.C, E = item.E}
于 2010-05-28T13:22:51.357 に答える