@@ -25,10 +25,10 @@ void AddSettersFromBindings(IEnumerable<MemberBinding> bindings, string path)
2525 switch ( node . BindingType )
2626 {
2727 case MemberBindingType . Assignment :
28- AddSettersFromAssignment ( ( MemberAssignment ) node , subPath ) ;
28+ AddSettersFromAssignment ( ( MemberAssignment ) node , subPath ) ;
2929 break ;
3030 case MemberBindingType . MemberBinding :
31- AddSettersFromBindings ( ( ( MemberMemberBinding ) node ) . Bindings , subPath ) ;
31+ AddSettersFromBindings ( ( ( MemberMemberBinding ) node ) . Bindings , subPath ) ;
3232 break ;
3333 default :
3434 throw new InvalidOperationException ( $ "{ node . BindingType } is not supported") ;
@@ -53,10 +53,10 @@ void AddSettersFromAnonymousConstructor(NewExpression newExpression, string path
5353 switch ( argument . NodeType )
5454 {
5555 case ExpressionType . New :
56- AddSettersFromAnonymousConstructor ( ( NewExpression ) argument , subPath ) ;
56+ AddSettersFromAnonymousConstructor ( ( NewExpression ) argument , subPath ) ;
5757 break ;
5858 case ExpressionType . MemberInit :
59- AddSettersFromBindings ( ( ( MemberInitExpression ) argument ) . Bindings , subPath ) ;
59+ AddSettersFromBindings ( ( ( MemberInitExpression ) argument ) . Bindings , subPath ) ;
6060 break ;
6161 default :
6262 _assignments . Add ( subPath . Substring ( 1 ) , Expression . Lambda ( argument , _parameters ) ) ;
@@ -121,15 +121,25 @@ public static Expression PrepareExpressionFromAnonymous<TSource>(Expression sour
121121 if ( expression == null )
122122 throw new ArgumentNullException ( nameof ( expression ) ) ;
123123
124- // Anonymous initializations are not implemented as member initialization but as plain constructor call.
125- var newExpression = expression . Body as NewExpression ??
124+ // Anonymous initializations are not implemented as member initialization but as plain constructor call, potentially wrapped in a Convert expression
125+ var newExpression = UnwrapConvertExpression ( expression . Body ) as NewExpression ??
126126 throw new ArgumentException ( "The expression must be an anonymous initialization, e.g. x => new { Name = x.Name, Age = x.Age + 5 }" ) ;
127127
128128 var instance = new DmlExpressionRewriter ( expression . Parameters ) ;
129129 instance . AddSettersFromAnonymousConstructor ( newExpression , "" ) ;
130130 return PrepareExpression < TSource > ( sourceExpression , instance . _assignments ) ;
131131 }
132132
133+ private static Expression UnwrapConvertExpression ( Expression expression )
134+ {
135+ if ( expression is UnaryExpression ue && ue . NodeType == ExpressionType . Convert )
136+ {
137+ return ue . Operand ;
138+ }
139+
140+ return expression ;
141+ }
142+
133143 public static Expression PrepareExpression < TSource > ( Expression sourceExpression , IReadOnlyDictionary < string , Expression > assignments )
134144 {
135145 var lambda = ConvertAssignmentsToBlockExpression < TSource > ( assignments ) ;
0 commit comments