Arbejdsglæde Arbejdsglæde - 11 days ago 7
C# Question

Glass Mapper v4 InferType Cast issue

I can't understand why Glass Mapper can't cast object in correct way like described here
I have next classes

public class BC
{
[SitecoreId]
public virtual ID Id { get; set; }
}

public class WB : BC
{
[SitecoreField(FieldName = "P1")]
public virtual Glass.Mapper.Sc.Fields.Link P1 { get; set; }
}

[SitecoreType(TemplateId = "{XXX}", AutoMap = true, EnforceTemplate = SitecoreEnforceTemplate.Template)]
public class AAA : WB
{
public virtual string AAAP1 { get; set; }
public virtual DateTime AAAP2 { get; set; }
}
[SitecoreType(TemplateId = "{VVV}", AutoMap = true, EnforceTemplate = SitecoreEnforceTemplate.Template)]
public class BBB : WB
{
public virtual string BBBp1 { get; set; }
public virtual DateTime BBBp2 { get; set; }
}

[SitecoreType(TemplateId = "{YYY}", AutoMap = true)]
public class RazorRenderClass: BC
{
[SitecoreChildren(InferType = true)]
public virtual IEnumerable<WB> Children { get; set; }

[SitecoreChildren(InferType = true)]
public virtual IEnumerable<AAA> AAACh { get; set; }

[SitecoreChildren(InferType = true)]
public virtual IEnumerable<BBB> BBBCh { get; set; }
}


at razor view I can't get AAA or BBB objects if I use Children property,

@foreach (var child in Model.Children)
{
if (child is BBB)
{
var news = child as BBB;
<li>
11
</li>
}
else if (child is AAA)
{
var evt = child as AAA;
<li>
222
</li>
}
}


What is more interesting, if I use call to BBBCh or AAACh properties at cshtml, I can see(at debug) that Children property contains correct items (object) but if I try to get any item from Children property like

var detailWidget = Model.Children.FirstOrDefault();


it would cast to WB class.
What I can do with it ?

Answer

I'm having the exact same problem, with version 4.0.5.54.

My hack around solution was to specify the subtypes as properties like you did with AAACh and BBBch. But setting up without lazy loading them.

[SitecoreType(TemplateId = "{YYY}", AutoMap = true)]
public class RazorRenderClass: BC
{                      
    [SitecoreChildren(InferType = true, IsLazy = false)]
    public virtual IEnumerable<WB> Children { get; set; }

    [SitecoreChildren(InferType = true, IsLazy = false)]
    public virtual IEnumerable<AAA> AAACh { get; set; }

    [SitecoreChildren(InferType = true, IsLazy = false)]
    public virtual IEnumerable<BBB> BBBCh { get; set; }
}

I really don't like that I have to specify, AAACh and BBBch as property. In glassmapper v3 the following would have sufficed.

[SitecoreType(TemplateId = "{YYY}", AutoMap = true)]
public class RazorRenderClass: BC
{                      
    [SitecoreChildren(InferType = true)]
    public virtual IEnumerable<WB> Children { get; set; }
}