Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Evangelos Lolos 7 posts 98 karma points
    Jan 18, 2018 @ 14:00
    Evangelos Lolos
    1

    ModelsBuilder: best way to get property alias from generated models

    At the moment, the best way to get a property alias based on a generated model is to use

    var propertyType = ModelClassName.GetModelPropertyType(d => d.PropertyName);
    var alias = propertyType.PropertyTypeAlias;
    

    Getting the alias like this allows you to not depend on magic strings in many cases, for example when calling IContent.SetValue().

    I've tried to come up with a general solution for this, so I first created a new method on each partial class that extends a generated model. Given that large solutions can contain many model classes however, I thought a more appropriate solution could be found.

    After spending some time on this, I realised that any reusable code would have to be put in the base class that all generated models inherit from, which of course I couldn't extend.

    In the process of reviewing the code for this on GitHub, I also realised that the GetModelPropertyType() method call is hitting the database, which in my opinion isn't ideal.

    Does anyone have any suggestions about how this can be done in a better way?

    I've thought about using Reflection to read the property attributes, but a more robust solution would be for the generated models to add one constant per property, for example:

    public const string BodyTextPropertyAlias = "bodyText";
    
    [ImplementPropertyType(BodyTextPropertyAlias)]
    public IHtmlString BodyText
    {
        get { return this.GetPropertyValue<IHtmlString>(BodyTextPropertyAlias); }
    }
    

    as they do now for the model class:

    public new const string ModelTypeAlias = "documentTypeAlias";
    

    which however seems like something that the ModelsBuilder would have to take care of.

Please Sign in or register to post replies

Write your reply to:

Draft