Search code examples
sitecoreglass-mapper

Sitecore convert MediaItem to Image in glass mapper


So, I am creating a content importer to pull content in from an external source into sitecore.

I create an image like so:

        MediaCreatorOptions options = new MediaCreatorOptions();
        options.FileBased = false;
        options.IncludeExtensionInItemName = false;
        options.KeepExisting = false;
        options.Versioned = false;
        options.Destination = sitecorePath +  mediaItemName;
        options.Database = Factory.GetDatabase("master");
        using (new SecurityDisabler())
        {
            MediaCreator creator = new MediaCreator();
            global::Sitecore.Data.Items.MediaItem mediaItem = creator.CreateFromFile(fileName, options);
        }

This does happily create the media item in sitecore and I can browse it in the media library.

The next step is to create the actual content page. I do stuff like this:

 var sitecoreModel = new NewsArticleForImport();
 sitecoreModel.Summary = articleContent.Summary;
 sitecoreModel.Headline = articleContent.Headline; 

 using (new SecurityDisabler()) {
        masterService.Create(newsRootItem, sitecoreModel);
 }

And this works fine.

The problem comes when I want to assign my image to my page. The question therefore is, how do I convert a MediaItem to a Glass.Mapper.Sc.Fields.Image, so I can assign it to my page?


Solution

  • Assuming the following models:

    public class NewsFolder
    {
        public virtual Guid Id { get; set; }
    }
    
    [SitecoreType(TemplateId = "{A874228E-B909-4164-8F4A-7DDA5ABA64AB}", AutoMap = true)]
    public class NewsItem
    {
        public virtual Guid Id { get; set; }
        public virtual Image Image { get; set; }
        public virtual string Name { get; set; }
    }
    

    The following code will assign a media item to the image field:

    var database = Sitecore.Configuration.Factory.GetDatabase("master");
    var sitecoreService = new SitecoreService(database);
    var myNewImage = new MediaItem(database.GetItem("{831D2FDF-98A9-46AD-AFC8-AF4918213068}"));
    
    var parent = sitecoreService.GetItem<NewsFolder>("/sitecore/content/home");
    
    var newNews = new NewsItem();
    newNews.Name = "New News";
    newNews.Image = new Image();
    newNews.Image.MediaId = myNewImage.ID.Guid;
    
    using (new SecurityDisabler())
    {
        sitecoreService.Create(parent, newNews);
    }