如何将标准值应用于使用Glass.Mapper创建的项

本文关键字:Mapper Glass 创建 标准值 应用于 | 更新日期: 2023-09-27 18:28:31

我通过Glass.Mapper创建了一个Sitecore项目,如下所示:

var homeItem = sitecoreContext.GetHomeItem<HomeItem>();
// Create the car item
ICar car = sitecoreService.Create(homeItem.BooksFolder, new Car { Tires = 4, Seats=4});

这是有效的,除非Car模板上的标准值没有应用,或者如果应用了,它们将立即被新的Car属性覆盖。因此,如果Car对象的Color属性的值为null,则该null将被写入字段,而不是Car模板上标准值中的"绿色"值。

我已经通过Glass.Mapper找到了一种合理的方法来实现这一点,但一无所获。有没有办法通过Glass.Mapper做到这一点?

如何将标准值应用于使用Glass.Mapper创建的项

有一种方法可以做到这一点,使用Create方法的覆盖,如下所示:

T Create<T, TK>(TK parent, string newName, Language language = null, bool updateStatistics = true, bool silent = false) where T : class where TK : class;

所以你的代码看起来像这样:

var homeItem = sitecoreContext.GetHomeItem<HomeItem>();
var carName = "Some New Name";
// Create the car item
// I don't know what the type of BooksFolder is so you would put that in the place of Folder.
ICar car = sitecoreService.Create<Car, Folder>(homeItem.BooksFolder, carName);
car.Tires = 4;
car.Seats = 4;
sitecoreService.Save(car);

我们遇到了同样的问题,这就是我们解决问题的方法。

您可以通过调用封装在EditContext中的Sitecore的reset()方法将想要的字段重置回其标准值。

var homeItem = sitecoreContext.GetHomeItem<HomeItem>();
// Create the car item
ICar car = sitecoreService.Create(homeItem.BooksFolder, new Car { Tires = 4, Seats=4});
using(new EditContext())
{
    car.Fields["Color"].Reset();
}

请参阅http://firebreaksice.com/how-to-reset-individual-sitecore-fields-to-standard-values/