How to convert dynamic value to type value in expression
Asked Answered
T

2

6
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?

Tiffaneytiffani answered 17/4, 2018 at 11:38 Comment(4)
Why do you need this?Huesman
I'm curious why all the downvotes on this question? Aside from the premise being odd, it's a valid question.Boman
@Boman I agree. I suspect that downvoters did not fully understand the question.Lovely
@dasblinkenlight Phew, I thought I was missing something obvious for a while!Boman
S
4

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.

Shrapnel answered 17/4, 2018 at 11:45 Comment(0)
L
3

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.

Lovely answered 17/4, 2018 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.