2

I'm trying to invoke a C# library method from PowerShell that has the following signature:

public void Load<T>(T thing, params Expression<Func<T, object>>[] retrievals);

For the 'retrievals' parameter, I only want to pass just one Expression argument, but when I do, PowerShell gives me the following error:

Cannot find an overload for "Load" and the argument count: "2".

I'm trying to use this:

$context.Load($thing, @($expressionTree1))

It keeps throwing that error.

I'm using PowerShell 5 and the C# library is the client side object model for SharePoint 2016.

Any ideas?

1
  • 2
    The second parameter must be an array of Expression<Func<T, object>>. Commented Aug 14, 2018 at 7:36

1 Answer 1

1

It should be shortest solution in your case.

$code = 
@'
    using System;
    using System.Linq.Expressions;

    public class Entity
    {
        public string Property1 { get; set; }
        public int Property2 { get; set; }
    }

    public class TestClass
    {
        public void Load<T>(T thing, params Expression<Func<T, object>>[] retrievals)
        {
            foreach (var retrieval in retrievals)
            {
                System.Console.WriteLine("Retrieval: " + retrieval);
            }
        }

        private static Expression<Func<T, object>> FuncToExpression<T>(Func<T, object> f)  
        {  
            return x => f(x);  
        } 

        public void Load2<T>(T thing, params Func<T, object>[] retrievals)
        {
            var funcs = new Expression<Func<T, object>>[retrievals.Length];

            for (int i = 0; i < retrievals.Length; i++)
            {
                funcs[i] = FuncToExpression(retrievals[i]);
            }

            this.Load<T>(thing, funcs);
        }

        public void Test1()
        {
            Entity entity = new Entity();
            this.Load<Entity>(entity, e => e.Property1, e => e.Property2);
        }
    }
'@

There is helper method Load2 but you can easly rewrite it to PowerShell. The key is another helper method FuncToExpression. It's possible to compile Linq expression "by hand" but it's much more complicated.

Sample of use:

    Add-Type -TypeDefinition $code -Language CSharp
    $o = New-Object TestClass
    $o.Test1()
    $entity = New-Object Entity
    $func1 = [Func`2[Entity, object]]{ param($e) $e.Property1 }
    $func2 = [Func`2[Entity, object]]{ param($e) $e.Property2 }
    $o.Load2($entity, [Func`2[Entity, object][]]@($func, $func2))
Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Though I wish there was a more PowerShell'y way of doing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.