Persist IContent instances
Describes how to save and load IContent instances through IContentRepository.
You can save and load IContent
instances through IContentRepository
. The most typical content instance is a type inheriting PageData
. You can load and save content types other than pages, but those content instances do not display in the editorial interface's page tree.
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. You can save each comment as an IContent
under the commented page. 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 PropertyDataCollection();
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 {
get {
return _properties;
}
}
public bool IsNull {
get {
return _properties.Count == 0;
}
}
#endregion
}
Save and load comment
The following example creates a Comment
instance, saves it, and re-loads it. Use IContentRepository
to create, load, and save content instances.
public class CommentHandler {
private IContentRepository _contentRepository;
public CommentHandler(IContentRepository contentRepository) {
_contentRepository = contentRepository;
}
public Comment CreateAComment() {
var comment = _contentRepository.GetDefault < Comment > (PageReference.RootPage, LanguageSelector.AutoDetect());
comment.Name = "acomment";
comment.User.Email = "[email protected]";
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);
System.Diagnostics.Debug.Assert(comment.User.Email == loadedComment.User.Email);
System.Diagnostics.Debug.Assert(comment.Body == loadedComment.Body);
return comment;
}
}
Updated 7 months ago