How to get Sitecore Data Item ID for Automapped Glass item C#

1.5k Views Asked by At

I have an automapped class that inherits GlassBase. The fields are automatically pulled from Sitecore and mapped to the class. I need to get the ID of the data item that the fields are being pulled from, but I'm not sure how.

In other projects I've had classes that inherit from GlassControl and I can get GlassItem.Id, but I don't have GlassControl in this project and I'm using GlassBase instead. How can I get the idea of the glass item that's being used?

public class MostRead : GlassBase
{
    private readonly IPersonifyUserContext _userContext;
    private readonly ISitecoreSearchProvider _searchProvider;
    private readonly ISitecoreContext _sitecoreContext;
    private readonly ICacheProvider _cacheProvider;
    private readonly I___Global_Page_Configuration _currentItem;

    public MostRead(IPersonifyUserContext userContext,ISitecoreContext context, ISitecoreSearchProvider searchProvider,ICacheProvider cache)
    {
        _cacheProvider = cache;
        _userContext = userContext;
        _searchProvider = searchProvider;
        _sitecoreContext = context;
        _currentItem = _sitecoreContext.GetCurrentItem<I___Global_Page_Configuration>();
    }
    [TopicsQueryAttirbute]
    public IEnumerable<ITopic> AllTopics { get; set; }

    [SitecoreField(IMost_ReadConstants.CountFieldName)]
    public int Count { get; set; }

    [SitecoreField(IMost_ReadConstants.PastXDaysFieldName)]
    public int Days { get; set; }

    [SitecoreField(IMost_ReadConstants.TopicsFieldName)]
    public IEnumerable<Guid> Topics { get; set; }

    [SitecoreField(IMost_ReadConstants.TitleFieldName)]
    public string Title { get; set; }

    [SitecoreField(IMost_ReadConstants.SiteFieldName)]
    public string Site { get; set; }
}
1

There are 1 best solutions below

0
On BEST ANSWER

GlassBase should contain a property called Id:

public abstract class GlassBase : IGlassBase
{
    [SitecoreId]
    public virtual Guid Id{ get; private set;}

    // Rest of class
}

Since your MostRead class inherits from GlassBase you can access the Id property just like you would normally access a property:

Inside the class:

// 'this' is redundant, but you could still use it
var id = this.Id;
// or
var id = Id;

Outside the class:

// Whatever your MostRead variable name is...
var mostRead = new MostRead();

var id = mostRead.Id;