Reputation: 4376
I have a multilist field on an item that can contain items from different templates. I was wondering if there was any way to map this field in such a way that the objects are mapped to the correct model based on their template. So for example:
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;}
}
In this instance I'd like the Participants
property to contain Student
and Professor
objects since they implement the Fullname
property differently.
Upvotes: 3
Views: 1986
Reputation: 2422
You can use infer types in Glass.mapper, Inferred types allows you to load a more specific type based on the template of the item being loaded. :
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;}
}
Notice that i added AutoMap = true
in your classes atrributes, and changed your multilist property attribute to be like:
[SitecoreField(Setting = SitecoreFieldSettings.InferType)]
For more details, go to mike tutorials here: http://glass.lu/docs/tutorial/sitecore/tutorial17/tutorial17.html
Edit:
You need to include your assembly in configurations loader, find the GlassMapperScCustom class in your solution. You should then update the GlassLoaders method:
public static IConfigurationLoader[] GlassLoaders()
{
var attributes = new AttributeConfigurationLoader("Your assembly name");
return new IConfigurationLoader[] {attributes };
}
Upvotes: 6