gpt4 book ai didi

sitecore - 将多列表字段映射到不同模板的对象

转载 作者:行者123 更新时间:2023-12-02 22:11:34 25 4
gpt4 key购买 nike

我的项目有一个多列表字段,其中可以包含来自不同模板的项目。我想知道是否有任何方法可以映射此字段,以便根据模板将对象映射到正确的模型。例如:

public interface IPerson
{
string FullName {get; set;}
}

[SitecoreType(TemplateId="....")]
public class Professor
{
[SitecoreField]
public string Prefix {get; set;}
[SitecoreField]
public string FirstName {get; set;}
[SitecoreField]
public string LastName {get; set;}

public string FullName
{
return string.format("{0} {1} {2}", Prefix, FirstName, LastName)
}
}

[SitecoreType(TemplateId="....")]
public class Student
{
[SitecoreField]
public string FirstName {get; set;}
[SitecoreField]
public string LastName {get; set;}

public string FullName
{
return string.format("{0} {1}", FirstName, LastName)
}
}

[SitecoreType(TemplateId="....")]
public class ClassSession
{
[SitecoreField]
public IEnumerable<IPerson> Participants {get; set;}
}

在本例中,我希望 Participants 属性包含 StudentProfessor 对象,因为它们实现了 Fullname code> 属性不同。

最佳答案

您可以在 Glass.mapper 中使用推断类型,推断类型允许您根据正在加载的项目的模板加载更具体的类型。 :

public interface IPerson
{
string FullName {get; set;}
}

[SitecoreType(TemplateId="....", AutoMap = true)]
public class Professor : IPerson
{
[SitecoreField]
public string Prefix {get; set;}
[SitecoreField]
public string FirstName {get; set;}
[SitecoreField]
public string LastName {get; set;}

public string FullName
{
return string.format("{0} {1} {2}", Prefix, FirstName, LastName)
}
}

[SitecoreType(TemplateId="....", AutoMap = true)]
public class Student : IPerson
{
[SitecoreField]
public string FirstName {get; set;}
[SitecoreField]
public string LastName {get; set;}

public string FullName
{
return string.format("{0} {1}", FirstName, LastName)
}
}

[SitecoreType(TemplateId="....", AutoMap = true)]
public class ClassSession
{
[SitecoreField(Setting = SitecoreFieldSettings.InferType)]
public IEnumerable<IPerson> Participants {get; set;}
}

请注意,我在您的类属性中添加了 AutoMap = true ,并将您的多列表属性更改为:

[SitecoreField(Setting = SitecoreFieldSettings.InferType)]

有关更多详细信息,请访问此处的麦克风教程: http://glass.lu/docs/tutorial/sitecore/tutorial17/tutorial17.html

编辑:

您需要将程序集包含在配置加载器中,在解决方案中找到 GlassMapperScCustom 类。然后您应该更新 GlassLoaders 方法:

public static IConfigurationLoader[] GlassLoaders()
{
var attributes = new AttributeConfigurationLoader("Your assembly name");

return new IConfigurationLoader[] {attributes };
}

关于sitecore - 将多列表字段映射到不同模板的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com