HomeDev GuideRecipesAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubNuGetDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Persist IContent instances

Describes how to save and load IContent instances through IContentRepository.

Save and load IContent instances through IContentRepository. The most typical content instance is a type inheriting PageData. Load and save content types other than pages, but those content instances do not appear in the editorial interface page tree.

📘

Note

PageReference is obsolete in CMS 13. Use ContentReference instead.

Each IContent stored in the Optimizely Content Management System (CMS) content database must have a corresponding ContentType registered. Classes annotated with the ContentType attribute are automatically scanned for and registered during initialization.

The following example uses the Comment class to define and persist a Comment type. To implement comment functionality, each comment is saved as an IContent under the page that is commented. However, the comments do not display in the page tree.

Define a comment content type

[ContentType]
public class CommentUser : BlockData
{
    public virtual string Email { get; set; }

    public virtual string Username { get; set; }
}

[ContentType]
public class Comment : IContent
{
    public virtual CommentUser User { get; set; }

    public virtual string Body { get; set; }

    #region IContent

    private PropertyDataCollection _properties = new();

    public string Name { get; set; }

    public ContentReference ContentLink { get; set; }

    public ContentReference ParentLink { get; set; }

    public Guid ContentGuid { get; set; }

    public int ContentTypeID { get; set; }

    public bool IsDeleted { get; set; }

    public PropertyDataCollection Property => _properties;

    #endregion
}

Save and load a comment

The following example creates a Comment instance, saves it, and reloads it. Use IContentRepository to create, load, and save content instances.

public class CommentHandler(IContentRepository contentRepository)
{
    public Comment CreateAComment()
    {
        var comment = contentRepository.GetDefault<Comment>(ContentReference.RootPage);
        comment.User.Email = "[email protected]";
        comment.User.Username = "[email protected]";
        comment.Name = "acomment";       
        comment.Body = "This is a comment";

        var contentLink = contentRepository.Save(comment, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);
        var loadedComment = contentRepository.Get<Comment>(contentLink);

        Debug.Assert(comment.User.Email == loadedComment.User.Email);
        Debug.Assert(comment.Body == loadedComment.Body);

        return comment;
    }
}