Search code examples
c#asp.net-mvcsitecoreglass-mapper

Error when casting class 'Unable to cast'


Im trying to cast entity class which inherits base class but its returning null.

Below is the code snippet class

public class CallItem : CallItemBase {

 [SitecoreField("TitleLink")]
 public virtual Link TitleLink { get; set; }

 SitecoreField("Image")]
 public virtual Image Image { get; set; }

 }

Razor view

     @foreach (var i in Model.CallItems)
     {
         var item = i as CallItem; //Its null even though i is not null
     }

CallItems is collection of CallItemBase

Forgot to mention that CallItem has glassmapper properties.


Solution

  • This is glass mapper InferType, to make it work you need to register your model assembly, to do that go to App_Start/GlassMapperScCustom.csand add your assembly inside GlassLoaders Method:

    public static IConfigurationLoader[] GlassLoaders(){
    
            /* USE THIS AREA TO ADD FLUENT CONFIGURATION LOADERS
             * 
             * If you are using Attribute Configuration or automapping/on-demand mapping you don't need to do anything!
             * 
             */
            var attributes = new SitecoreAttributeConfigurationLoader("YourAssembly");
            return new IConfigurationLoader[]{ attributes };
        }
    

    and in the class where you define callitems as children you should add attribute InferType=true :

    public class YourCollectionClass
        {
            [SitecoreChildren(InferType = true)]
            public virtual IEnumerable<CallItemBase> CallItems{ get; set; }
        }