OData / OData/ModelBuilder

MaxLengthAttributeEdmPropertyConvention to allow inheritance from MaxLengthAttribute

Open
#44 1 comment 0 reactions 1 assignee View on GitHub

@WanjohiSammy is already working on this.

Since Oct 22, 2024.

follow-up investigation
Dominant language
C#
Stars
22
Forks
24
PR merge metrics
No merged PRs in 30d

Description

MaxLengthAttributeEdmPropertyConvention takes into account MaxLength attribute and sets MaxLength property where appropriate.
I have a number of pattern-attributes like this (only an example):

class ShortLengthStringAttribute : MaxLengthAttribute
{
    public ShortLengthString() : base(50)
    {
        this.ErrorMessage = "Max length is 50 characters";
    }
};
class LongLengthStringAttribute : MaxLengthAttribute
{
    public LongLengthString() : base(255)
    {
        this.ErrorMessage = "Max length is 255 characters";
    }
};

In this case MaxLengthAttributeEdmPropertyConvention ignores my attributes. Is it possible to allow descendants of MaxLengthAttribute here?

    public MaxLengthAttributeEdmPropertyConvention()
        : base(attribute => attribute.GetType() == typeof(MaxLengthAttribute), allowMultiple: false)
    {
    }
Assemblies affected

Microsoft.OData.ModelBuilder.dll 2.0.0

Reproduce steps

Make a model with

 [ShortLengthString] string ShortString { get; set; }
Expected result

MaxLength should be automatically set to 50 in the model.

Actual result

It is not set

Additional detail

I know there are workarounds. For example I can do it manually. Or I can do something like this:

        builder.OnModelCreating = (builder) =>
        {
            foreach (var structType in builder.StructuralTypes)
            {
                foreach (var property in structType.Properties.OfType<LengthPropertyConfiguration>())
                {
                    var pp = property.PropertyInfo.GetCustomAttribute<MaxLengthAttribute>();
                    if (pp != null)
                    {
                        property.MaxLength = pp.Length;
                    }
                }
            }
        };

But I don't think it is natural.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.