Friday, January 16, 2009

Obscure Error: IDataErrorInfo causes NullReferenceException in ASP.NET Dynamic Data

I'm using ASP.NET Dynamic Data against an existing Linq-to-SQL data context.  For some of the table classes, I implement IDataError info for validation in a different (non-dynamic data) part of the app.  For these tables, browsing to the List.aspx page was throwing a nullreferenceexception from 'MetaColumn'.   I debugged the issue down to the default indexer specified by IDataErrorInfo.  I'm not a fan of this indexer anyway - it's non-obvious that myClass["property"] should return an error, and in some cases conflicts with other, more sane default indexers.  I'd prefer myClass.Errors["property"].  Anyway, I degress-  I was about to give up, when I decided to try an explicit implementation of IDataErrorInfo.  Viola! No error. 

So, if you get 'Object not set to instance' using ASP.NET Dynamic Data, and your class implements IDataErrorInfo, or has some other default indexer, try changing from this:

public string this[string columnName]

To this:

string IDataErrorInfo.this[string columnName]

This is probably a better way to implement anyway.

No comments: