CodeBox
CodeBox

Reputation: 446

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.

Upvotes: 0

Views: 759

Answers (3)

Ayman Barhoum
Ayman Barhoum

Reputation: 1255

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; }
    }

Upvotes: 2

Demonia
Demonia

Reputation: 342

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.

Upvotes: 1

Stormhashe
Stormhashe

Reputation: 704

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.

Upvotes: 1

Related Questions