I've been banging my head against this all day and I've run out of ideas. Basically because glass.mapper doesn't appear to support branch templates I'm creating a sitecore item using the standard DB methods. I then use GlassCast<T>()
to give me a properly typed object.
This typed object appears to contain a id field however, when I try and save the object I get the error:
You cannot save a class that does not contain a property that represents the item ID
Here's my method:
private Glass.Mapper.Sc.ISitecoreService SitecoreService;
public T CreateFromBranch<T>(string parentPath, string itemName,
Guid branchTemplateId) where T : class, ICmsItem
{
Item parent = SitecoreService.Database.GetItem(parentPath);//SitecoreService.GetItem<Item>(parentPath);
if (parent == null)
throw new NullReferenceException("Cannot load item to act as parent from path: " + parentPath);
BranchItem branch = SitecoreService.Database.GetItem(new ID(branchTemplateId));
if (branch == null)
throw new ApplicationException("Failed ot find template branch with the id:" + branchTemplateId);
Item itemFromBranch = parent.Add(itemName, branch);
if (itemFromBranch == null)
throw new ApplicationException("Failed to create item from branch template. BranchId: " + branchTemplateId);
itemFromBranch.Fields.ReadAll();
T typedItem = itemFromBranch.GlassCast<T>();
//Id is accessible here and is the id of the item that is created!
Guid id = typedItem.Id;
typedItem.DisplayName = itemDisplayName;
//Exception thrown here!
SitecoreService.Save(typedItem);
return typedItem;
}
Interface:
[SitecoreType(AutoMap = true)]
public interface ICmsItem
{
//Id flagged here! Same in the concrete class
[SitecoreId]
Guid Id { get; }
[SitecoreInfo(SitecoreInfoType.Name)]
string Name { get; set; }
[SitecoreInfo(SitecoreInfoType.DisplayName)]
string DisplayName { get; set; }
[SitecoreInfo(SitecoreInfoType.Path)]
string Path { get; set; }
[SitecoreInfo(SitecoreInfoType.TemplateId)]
Guid TemplateId { get; set; }
[SitecoreField(FieldName = "__Never publish")]
bool NeverPublish { get; set; }
[SitecoreField(FieldName = "__Icon")]
string CmsIcon { get; set; }
[SitecoreField(FieldName = "__Workflow")]
Guid? Workflow { get; set; }
[SitecoreField(FieldName = "__Workflow state")]
Guid? WorkflowState { get; set; }
[SitecoreField(FieldName = "__Sortorder")]
int SortOrder { get; set; }
}
the item is created in sitecore. But it does not have the updated display name. If I alter the code so that it doesn't use glass mapper at all:
if (!string.IsNullOrWhiteSpace(itemDisplayName))
{
itemFromBranch.EditField("__Display name", itemDisplayName);
}
It works!
Anybody got any idea what I'm doing wrong here?
set
modifier to theId
property to see if that makes any difference. – Smyth