Get to Part from ContentItem

Topics: Writing modules
Jul 13, 2012 at 8:25 PM

In my controller, I'm calling a ContentItem as

var episode = _orchardServices.ContentManager.Get(episodeId);

Is there a way to get to the Part properties for that item?

The EpisodePart contains a ShowPart and I need to get to the Id of the ShowPart.

I see that I can call episode.Parts...but I don't know what to put after this to get the actual Part.

Any help you can give is greatly appreciated. I thought this would be easier than passing in the showId from the View.

Developer
Jul 13, 2012 at 10:20 PM
Edited Jul 13, 2012 at 10:21 PM

Cast your episode to dynamic, then you can easily access your parts and properties:

var episode = (dynamic)_orchardServices.ContentManager.Get(episodeId);

var showPartId = episode.ShowPart.Id;

However, if I'm not mistaken, the Id of any content part will always match the Id of the content item to which it is attached. So in this particular case, you wouldn't have to access the ShowPart at all: just use the Id of episode.

Jul 16, 2012 at 4:13 AM

Awesome...thanks. I love how flexible dynamic can be.

Developer
Jul 16, 2012 at 9:21 AM

Or if you like static typing, then just use the

var episodePart = episode.As<EpisodePart>();

form. Don't forget to add the using Orchard.ContentManagement declaration to your code file as this method is an extension.

As for the Id, I'm not sure. If the part is attached to a ContentPartRecord, then the id will be the same as the content item's, but if it's a ContentPartVersionRecord then I think the Id changes, but there is a ContentItemRecord_id.

Developer
Jul 16, 2012 at 11:19 PM
Piedone wrote:

As for the Id, I'm not sure. If the part is attached to a ContentPartRecord, then the id will be the same as the content item's, but if it's a ContentPartVersionRecord then I think the Id changes, but there is a ContentItemRecord_id.

This is true from the db perspective, but if you look at ContentPart.cs, you'll see the Id property implemented as follows:

        /// <summary>
        /// The ContentItem's identifier.
        /// </summary>
        [HiddenInput(DisplayValue = false)]
        public int Id {
            get { return ContentItem.Id; }
        }

So when working with content parts, their Id matches the Id of the content item.