Search code examples
ormsitecorecode-generationglass-mappertds

Sitecore Glass mapper GetItem<TypeName>(guid) always return null


I saw a related question: Sitecore Glass Mapper always null

But unfortunately it does not give a solution for my case.

Here goes a code snippet:

var db = Factory.GetDatabase("master");
var context = new SitecoreContext();
// the ID of Needed item
var g = new Guid("{F21C04FE-8826-41AB-9F3C-F7BDF5B35C76}");
// just to test if it's possible to fetch item using db.GetItem
var i = db.GetItem(new ID(g), Language.Current, Sitecore.Data.Version.Latest);
// Grab item
var t = context.GetItem<Article>(g);

In the code above: i is not null t is null

Article is the simple class like:

[SitecoreType(TemplateId = "{4C4EC1DA-EB77-4001-A7F9-E4C2F61A9BE9}")]
public class Article
{
    [SitecoreField(FieldName = "Title")]
    public string Title { get; set; }
}

There are only one language installed in Sitecore - en, it has been specified in the web.config in the items as well.

Also I have added GlassMapperSc.Start(); to Application_Start in the Global.asax.cs and added my assembly to the list of included assemblies via var attributes = new AttributeConfigurationLoader(new[] { "Assembly.Name" }); and I succeeded to find my class in the SitecoreContext mappings.

It does not looks like a language issue, as stated in the link provided in the very beginning. And I'm struggling with it already for a pretty long time, but no luck...

Thank You!


Solution

  • I just noticed that you are using master db for the Sitecore DB and SitecoreContext for Glass.

    The SitecoreContext class will use the database that is defined by the Sitecore.Context.Database property at runtime. This probably means that it is using the web database.

    Can you check that you have published the item to the web database or instead using:

    var context = new SitecoreService("master");