Search code examples
c#xmllambdaexpression-trees

Expression.Assign Right Property Must be readable


Getting the following Arguement Exception ("Expression must be readableParameter name: right") running this code and cant figure out why.

This code is meant to create a delegate to take the Attributes in a XmlNode and map them to properties on an object.

private static Action<XmlNode, T>   createMapperFunction() {
            var props = typeof(T).GetProperties().ToArray();
            var xmlNodeParameter = Expression.Parameter(typeof(XmlNode), "x");
            var resultParameter = Expression.Parameter(typeof(T), "result");
         //   Expression.
            var exprList = new List<Expression>();
            for (int i = 0 ; i < props.Length ; i++) {
                if (props[i].PropertyType == typeof(string))
                    exprList.Add(Expression.Assign(Expression.Property(resultParameter,props[i].Name), 
                            Expression.Property(
                                Expression.Property(
                                    Expression.Property(xmlNodeParameter,"Attributes"), "ItemOf", Expression.Constant(props[i].Name)),"InnerText")));
            }
            var body = Expression.Block(exprList);
            return Expression.Lambda<Action<XmlNode, T>>(body, xmlNodeParameter, resultParameter).Compile();



        }

Solution

  • XmlAttribute.InnerText is write-only. Using XmlAttribute.InnerText as the right-side of an assignment won't work because the Assign expression can't read the value to assign it to the left-side.