InvalidCastException when building editor for a part

Topics: Troubleshooting, Writing modules
Jun 3, 2011 at 4:21 AM


In my AdminController Create() method for creating a forum thread I get an InvalidCastException when executing the following code:

 public ActionResult Create(int categoryId)
            var category = _categoryService.Get(categoryId,  VersionOptions.Latest).As<CategoryPart>();
            if (category == null)
                return HttpNotFound();

            var thread = Services.ContentManager.New<ThreadPart>("Thread");
            thread.CategoryPart = category;

            var post = Services.ContentManager.New<PostPart>("Post");
            post.ThreadPart = thread;

            dynamic model = Services.ContentManager.BuildEditor(thread);

            return View((object)model);

Creating a new thread works fine but when the ContentManager goes to create a new post it throws an InvalidCastException, with the part it is attempting to return being null?:

 public static class ContentCreateExtensions {

        /* Item creation extension methods */

        public static T New<T>(this IContentManager manager, string contentType) where T : class, IContent {
            var contentItem = manager.New(contentType);
            if (contentItem == null)
                return null;

            var part = contentItem.Get<T>();
            if (part == null)
                throw new InvalidCastException();

            return part;
Any ideas on what I am doing wrong?

Jun 3, 2011 at 9:11 AM

Looks like your PostPart is not being welded into the content item of type Post. Check to make sure that the part is included in the definition of your type, and also make sure that you have a driver for PostPart (otherwise Orchard might use a ContentPart to represent it).

Jun 7, 2011 at 1:32 AM

Thanks for the answer Hosamaly, but I think I've found the answers to my problems with this in a more recent discussion about posts/threads.

Jun 7, 2011 at 2:15 AM

Actually you were perfectly right Hosamaly. I had completely forgotten to define my Post item as a type in the Migrations class! Silly me.