使用不同模板的对象映射Multilist字段

时间:2014-08-29 13:02:47

标签: sitecore glass-mapper

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

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属性。

1 个答案:

答案 0 :(得分:4)

您可以在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 };
    }