Search code examples
.netentity-frameworkidataerrorinfo

EntityFramework and IDataErrorInfo : Default implementation for string Error


I have just been wondering if this (default) implementation for IDataErrorInfo.Error is good or evil in some ways:

public string Error
{
    get 
    {
        StringBuilder sb = new StringBuilder();

        foreach( PropertyInfo propertyInfo in GetType().GetProperties( System.Reflection.BindingFlags.Public ) )
        {
            String propertyError = this[ propertyInfo.Name ];

            if ( String.IsNullOrWhiteSpace( propertyError) == false )
            {
                if( sb.Length > 0 )
                {
                    sb.Append( Environment.NewLine );
                }

                sb.Append( String.Format( CultureInfo.InvariantCulture, "[{0}] - {1} ({2}"
                                            , propertyInfo.Name
                                            , propertyError
                                            , propertyInfo.GetValue( this ) ) );
            }
        }

        return sb.ToString();
    }
}

Besides of course the potential problem with GetValue, the missing check for NotMapped and the potential performance issue that can be mitigated by caching the properties in a static list.

Thanks

Mario


Solution

  • You pointed out the main drawbacks that makes the design fairly evil...

    Properties should not have much processing code, as the msdn guidelines suggests : Property Usage Guidelines.

    In this case, I suggests you to :

    1. Store the errors in a private string list (or whatever collection or dictionary that may fit well).
    2. Fill the list from the indexer property (the one that implement IDataErrorInfo)

    This way, the Error property will just have to concat the errors.