Kuroro
Kuroro

Reputation: 1931

How to convert dynamic value to type value in expression

public class Model1 {
    public String Value { get; set; }

}
public class Model2 {
    public dynamic Value { get; set; }
}

public static Expression<Func<Model2, Model1>> GetExpression() {
    return f => new Model1 {
        Value = f.Value
    };
}

I am writing a GetExpression() which convert Model2 property to Model1. When it comes to dynamic property, I try Convert.ToString(f.Value) or (String)f.Value but it said

"An expression tree may not contain a dynamic operation"

Anyone know what is the proper way to convert dynamic value to type value in expression?

Upvotes: 6

Views: 253

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

You can move the code that builds Model1 from Model2 into a method, and use that method in your expression, like this:

private static Model1 FromMolde2(Model2 m2) {
    return new Model1 { Value = m2.Value };
}
public static Expression<Func<Model2, Model1>> GetExpression() {
    return f => FromMolde2(f);
}

One side benefit of this approach is that the code that copies properties from Model2 into Model1 is available for reuse.

Another possibility is to give Model1 an additional constructor that takes Model2, but this would introduce a potentially undesirable dependency between the two classes.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062745

The only way to do this is to convince the expression compiler to overlook the dynamic:

return f => new Model1
{
    Value = (string)(object)f.Value
};

or

return f => new Model1
{
    Value = Convert.ToString((object)f.Value)
};

With anything else, there is going to be an implicit dynamic conversion, which isn't supported. This just does a hard cast instead.

However, frankly I wonder whether there's much value in f.Value being dynamic in the first place.

Upvotes: 4

Related Questions