开发者

Attributes of properties in MetadataType are ignored by EntLib Validation

It's an EntLib-Validator-issue again. I'm playing with EntLib 5.0 in C# and .Net 4.0 on XP pro.

I have some business objects (partial classes) generated by T4 templates. So I decided to put their validation attributes in buddy-classes by using MetadataTypeAttribute as definitely rec开发者_运维知识库ommended by the documentation of entLib 5.0 (msdn). But the Validator object I get from the ValidatorFactory doesn't know about the validation attributes, defined in the metadata-class.

The business object is defined like this:

[MetadataType(typeof(PatientMetadata))]
public partial class Patient
{
    private string _Name;
    private int _DiagnosisCount;

    public int DiagnosisCount
    {
        get
        {
            return _DiagnosisCount;
        }

        set
        {
            if (value != _DiagnosisCount)
            {
                _DiagnosisCount = value;
            }
        }
    }

    public string Name
    {
        get
        {
            return _Name;
        }

        set
        {
            if (value != _Name)
            {
                _Name = value;
            }
        }
    }
}

And the metadata class like this, according to documentation:

public class PatientMetadata
{
    [RangeValidator(4)]
    public int DiagnosisCount { get; set; }

    [StringLengthValidator(64, ErrorMessage = "Name must not exceed 64 chars.")]
    public string Name { get; set; }
}

If I know try to do validation this way:

    var factory = ValidationFactory.DefaultCompositeValidatorFactory;
    var validator = factory.CreateValidator<Patient>();

...then watching into validator (during debugging) already says, that it's just an AndCompositeValidator without any children validators. Again, if I put the validation attributes right in the Patient class, it works perfectly.

By now, I have no real idea, what I'm missing here, since I think doing everything according to the docs.

Thanks in advance to you guys!


The property names of the metadata class must match the property names of the main class.

In your case your metadata class should look like:

public class PatientMetadata
{
    [RangeValidator(0, RangeBoundaryType.Inclusive, 10, RangeBoundaryType.Ignore)]
    public int DiagnosisCount { get; set; }

    [StringLengthValidator(6, ErrorMessage = "Name must not exceed 6 chars.")]
    public string Name { get; set; }
}  

Also, the docs indicate the accepted approach is to declare all return types as object. However, the docs also talk about using properties but in their example use fields so take it under advisement. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜