Model with dynamic type properties

Asked

Viewed 112 times

2

I have a select on the bench that brings several items and loads everything into one model. The point is that one of the items, depending on how the select is done, is brought in a different type. Ex:

The property on the model:

public int procodigo { get; set; }

The content to be loaded in this property can be int or decimal, depending on the client’s action.

I could create two models, but I think it can be kind of messed up.

Thanks in advance!

  • 1

    Why not just use one decimal?

  • 1

    @Evandrosilva Because for some reason at the time of putting an integer number inside it gives Exception.

  • 1

    Only cast to decimal: decimal x = (decimal)y

  • 1

    @Juniordias Qual Exception?

  • 1

    @Ciganomorrisonmendez Essa Exception: "The specified cast from a materialized 'System.Int32' type to the 'System.Decimal' type is not Valid."

  • 1

    Like your table, why don’t you practice it?

Show 1 more comment

1 answer

4


Use the dynamic C#.

public dynamic procodigo { get; set; }

In that case, you don’t have to worry about which type will be stored. Both decimal how much int worked perfectly.

For more information see the documentation of msdn.

  • Just one observation: this is not the best solution when the data needs to be represented in the EF or a model for a Database Table.

  • Well, it worked here, I didn’t know this Dynamic. Thank you! @Evandrosilva.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.