0

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.

Ahmed Okour
  • 2,392
  • 1
  • 16
  • 31
CodeBox
  • 446
  • 4
  • 19

3 Answers3

2

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; }
    }
Ayman Barhoum
  • 1,255
  • 1
  • 16
  • 31
1

You can't auto cast an class based on its base class. You can do the other way around.

Example:

you have:

public class CallItemBase
{
    public int Prop1 {get;set;}
    public int Prop2 {get;set;}
    public int Prop3 {get;set;}
    public int Prop4 {get;set;}
}

public class CallItem : CallItemBase
{
    public int Prop5 {get;set;}
    public int Prop6 {get;set;}
}

If you cast a CallItemBase object to call item, the code would break when you tried to access Prop5 and Prop6, because they are not in the CallItemBase class.

but, if you have a CallItemBase list and try to cast its itens to CallItem, it would work, because CallItem has all the properties CallItemBase has, plus its own properties.

Stormhashe
  • 704
  • 6
  • 16
  • Its an glass mapper entity with additional properties which gets mapped when casting this works with older version of glass mapper but in current upgraded version 4.2 doesnt work – CodeBox Nov 03 '16 at 17:51
1

The keyword "as" return null if the type is not correct. You can cast an inherited class to a base class but not a base class to an inherited class.

there is many answer to this question. for example : Convert base class to derived class

One solution is to use a collection of CallItemBase and do it like this

 var item = i as CallItemBase;

or you just can convert your collection to a CallItem one.

Community
  • 1
  • 1
Demonia
  • 332
  • 3
  • 14