Lia*_*iam 4 c# generics sitecore glass-mapper
我整天都在努力应对,但我的想法已经用完了。基本上是因为glass.mapper似乎不支持分支模板,所以我正在使用标准DB方法创建一个sitecore项。然后我用GlassCast<T>(),我用来给我一个正确类型的对象。
此类型的对象似乎包含一个id字段,但是,当我尝试保存该对象时,出现错误:
您不能保存不包含代表商品ID的属性的类
这是我的方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
[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; }
}
Run Code Online (Sandbox Code Playgroud)
该项目是在sitecore中创建的。但是它没有更新的显示名称。如果我更改代码,使其根本不使用玻璃映射器:
if (!string.IsNullOrWhiteSpace(itemDisplayName))
{
itemFromBranch.EditField("__Display name", itemDisplayName);
}
Run Code Online (Sandbox Code Playgroud)
有用!
有人知道我在做什么错吗?
最后到达那里。这个问题实际上并不包含缺少的内容,但是我要给出一个答案,以防其他人陷在死胡同中!
我的问题实际上是具体的课程。我没有注意到的是,该类中还包含其他类:
public class V2Development : ICmsItem
{
.....
[SitecoreField]
public virtual IEnumerable<CallToActionButtonBase> CallToActionButtons { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
该CallToActionButtonBase类型没有一个ID领域!因此,玻璃映射器一直在整个依赖树中进行尝试,并尝试解析所有对象。然后,当它碰到这个对象时,它失败了,因为它没有一个ID(下次可以给我们一个更具建设性的错误消息吗,请GlassMapper先生?也许可以说是哪个对象丢失了ID?)
我的解决方法是添加一层抽象,所以我有两个对象,一个带有子对象,一个没有子对象。然后,我创建一个没有子对象的对象实例(一个接口可以完成类似的工作,但是,TBH,此解决方案在接口中游刃有余,我正尝试避免使用它)。