views:

22

answers:

1

I have an ObjectDataSource on a page that is producing the error "Object does not match target type" when its Insert method is invoked. From Googling this message, I believe this the message is deceptive and I'm actually getting a null reference error on the object that the ObjectDataSource is trying to invoke the method on, but I'm darned if I can figure out why.

<asp:ObjectDataSource ID="dsAddComment" runat="server"  
     DataObjectTypeName="BookCatalogue.InteractionDocuments.UserComment"
     SelectMethod="GetNewComment" TypeName="BookCatalogue.AddCommentPresenter"
     InsertMethod="AddComment"  OnObjectCreating="dsAddComment_ObjectCreating" />

The Type that is being called upon Insert is an AddCommentPresenter. The method AddComment is not static. If I change this to static, I don't get the error and the method is found without problem. When it's not static, the error occurs. That's whyI htink that the underlying problem is that somehow I'm not getting a valid instance of my Presenter class when the AddComment method is invoked.

My AddCommentPresenter class doesn't have a parameterless constructor. This will cause an error normally. To get around it I'm overriding the ObjectCreating event in my page's code-behind and assigning an instance of the Presenter class.

protected void dsAddComment_ObjectCreating(object sender, ObjectDataSourceEventArgs e) { e.ObjectInstance = presenter; }

I can step through my ObjectCreating method and it is a valid, non-null Presenter instance that's being passed into the e.ObjectInstance property.

My AddComment method has the correct signature.

    public void AddComment(UserComment newComment)
    {
        ...
    }

I've also checked the obvious things, like misspelling the type name on the aspx page, but all is correct there.

Anyone have any ideas? I must say that I find the ObjectDataSource class very difficult to work with....

A: 

A colleague found the cause of my problem. The AddCommentPresenter class in my web app was defined in the website's App_Code directory. For some reason, that was causing the error. Move it out of there, into the main directory of the website and the code worked. I can't find any mention in any ObjectDataSource documentation of this being a potential gotcha for the control, but there you go.

I've also been told that it should be possible to keep the class in the App_Code folder, but include the syntax ",__code" at the end of the TypeName. E.g.

TypeName="MyNamespace.MyType,__code" 

but personally, I didn't get that working when I tried it. Another post to an ASP.Net forum suggested changing the TypeName to

TypeName="_MyNamespace.MyType"

That didn't work for me, either. I ended up just pulling the class out of the App_Code folder.

Treighton