用于创建具有可变数量泛型类型参数的元组的表达式

huy*_*itw 5 c# linq-expressions

我正在尝试构建一个表达式,用于创建Tuple<>具有可变数量泛型类型参数的泛型实例。

生成实例的想法Tuple<>是根据具有 a 的属性为实体类型动态创建复合键值KeyAttribute。然后,复合键将用作Dictionary<object, TEntity>. 因此,应该为特定实体类型构建 lambda 表达式,并调用 lambda,传递 的实例TEntity以获取 a 形式的组合键Tuple<>

实体模型示例

public class MyEntityModel
{
    [Key]
    public string Key1 { get; set; }
    [Key]
    public Guid Key2 { get; set; }
    public int OtherProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

应该做什么表情

public Func<MyEntityModel, object> BuildKeyFactory()
{
    // This is how the LambdaExpression should look like, but then for a generic entity type instead of fixed to MyEntityModel
    return new Func<MyEntityModel, object>(entity => new Tuple<string, Guid>(entity.Key1, entity.Key2));
}
Run Code Online (Sandbox Code Playgroud)

但实体模型当然需要是泛型类型。

到目前为止我所拥有的

public Func<TEntity, object> BuildKeyFactory<TEntity>()
{
    var entityType = typeof(TEntity);

    // Get properties that have the [Key] attribute
    var keyProperties = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
        .Where(x => x.GetCustomAttribute(typeof(KeyAttribute)) != null)
        .ToArray();

    var tupleType = Type.GetType($"System.Tuple`{keyProperties.Length}");
    if (tupleType == null) throw new InvalidOperationException($"No tuple type found for {keyProperties.Length} generic arguments");

    var keyPropertyTypes = keyProperties.Select(x => x.PropertyType).ToArray();
    var tupleConstructor = tupleType.MakeGenericType(keyPropertyTypes).GetConstructor(keyPropertyTypes);
    if (tupleConstructor == null) throw new InvalidOperationException($"No tuple constructor found for key in {entityType.Name} entity");

    // The following part is where I need some help with...
    var newTupleExpression = Expression.New(tupleConstructor, keyProperties.Select(x => ????));

    return Expression.Lambda<Func<TEntity, object>>(????).Compile();
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我无法弄清楚我需要如何创建属性表达式来传递给调用Expression.New()(可能是一些东西Expression.MakeMemberAccess(Expression.Property()),但不知道如何TEntity从 lambda 参数传递实例)以及如何“链接” ' 这个电话Expression.Lambda。任何帮助将不胜感激!

Evk*_*Evk 3

你很接近。

// we need to build entity => new Tuple<..>(entity.Property1, entity.Property2...)
// arg represents "entity" above
var arg = Expression.Parameter(typeof(TEntity));
// The following part is where I need some help with...
// Expression.Property(arg, "name) represents "entity.Property1" above
var newTupleExpression = Expression.New(tupleConstructor, keyProperties.Select(c => Expression.Property(arg, c)));
return Expression.Lambda<Func<TEntity, object>>(newTupleExpression, arg).Compile();
Run Code Online (Sandbox Code Playgroud)