Is there an easy way to parse a (lambda expression) string into an Action delegate?

.net c# expression-trees linq parsing

Question

I have a method that alters an "Account" object based on the action delegate passed into it:

public static void AlterAccount(string AccountID, Action<Account> AccountAction) {
  Account someAccount = accountRepository.GetAccount(AccountID);
  AccountAction.Invoke(someAccount);
  someAccount.Save();
}

This works as intended...

AlterAccount("Account1234", a => a.Enabled = false);

...but now what I'd like to try and do is have a method like this:

public static void AlterAccount(string AccountID, string AccountActionText) {
  Account someAccount = accountRepository.GetAccount(AccountID);
  Action<Account> AccountAction = MagicLibrary.ConvertMagically<Action<Account>>(AccountActionText);
  AccountAction.Invoke(someAccount);
  someAccount.Save();
}

It can then be used like:

AlterAccount("Account1234", "a => a.Enabled = false");

to disable account "Account1234".

I've had a look at the linq dynamic query library, which seems to do more or less what I want but for Func type delegates, and my knowledge of Expression trees etc isn't quite good enough to work out how to achieve what I want.

Is there an easy way to do what I want, or do I need to learn expressions properly and write a load of code?

(The reason I want to do this is to allow an easy way of bulk updating account objects from a powershell script where the user can specify a lambda expression to perform the changes.)

Popular Answer

You may try this: Dynamic Lambda Expressions Using An Isolated AppDomain

It compiles a lambda expression using CodeDOM compiler. In order to dispose the in-memory assembly that gets created, the compiler runs on an isolated AppDomain. For the passing the expression through the domain boundary, it has to be serialized. Alas, Expression<> is not Serializable. So, a trick has to be used. All the details are explained in the post.

I'm the author of that component, by the way. I would like very much to hear your feedback from it.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why