Friday, 15 April 2011

c# - How to use an Expression<Func> to set a nested property? -


Then I have some code that sets the property on the object. This code is from an internal verification class which we are using in unit tests. Something like the code

can be supplied <0> private static zero SetDeepValue (object targetObject, the expression & lt; string & gt; propertyToSet of function, object valueToSet) { Var underlyingProperty = ((PropertyInfo) ((MemberExpression) propertyToSet.Body) .member); Built-in Property. Set Value (Target Object, Cost Costs); }

This code is a unit-test type environment, where we can then call

(CurrentTestCaseValue in String TestCaseSets) {BusinessObject MyCustomer = New BusinessObject () is used; Setup value (myCustomer, () => myCustomer.FirstName, Current TestCaseValue); ValidateBusinessRules (myCustomer); }

(Simplified code for brevity / complexity)

However, due to some refactorings, we are left with something like this:

  foreach (string current credentials value in test casease) {BusinessObject myCustomer = new BusinessObject (); SetDeepValue (myCustomer, () = & gt; myCustomer.NameInfo.First, Current TestCaseValue); ValidateBusinessRules (myCustomer); }  

Runs this code, we get the error.

object does not match the target type

I suspect that this is the first property instead of the name code Trying to call BusinessObject . How can I modify my code to handle this 'Nest' case?

After

Here you can usually change the string to "columnname 1. columnname 2" in a lambda expression x = & gt; X.ColumnName1.ColumnName2 :

  Expressions & lt; & Lt; T, Object & gt; & Gt; Prohibited property (string columnname) {// X parameter expansion para = expression Parameter (typef (t), "x"); // x.ColumnName1.ColumnName2 Expression Property = Columnname.LimP ('.') .Gregate & lt; String, Expression & gt; (Ultimate, (C, M) => Expression Property (C, M)); // x = & gt; X.ColumnName1.ColumnName2 expression & lt; Func & lt; T, Object & gt; & Gt; Lambda = expression. Lambda & lt; Func & lt; T, Object & gt; & Gt; (Expression. Conversion (property, type (object)), absolute); Return lambda; }  

(copied)


No comments:

Post a Comment