Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use SaveAndPublish from ContentService

I'm trying to save my IContent called child, but on this line(contentService.SaveAndPublish(child);) I get the following error: Object reference not set to an instance of an object.

if (child.HasProperty("navn"))
{
    child.SetValue("navn", worker.Name.ToString(), "da-dk");
}
contentService.SaveAndPublish(child);

This is how I define my contentService:
IContentService contentService = Umbraco.Core.Composing.Current.Services.ContentService;

And I'm finding the children like this:

long totalChildren;

IEnumerable<IContent> children = contentService.GetPagedChildren(filialsParent.Id, 0, 100, out totalChildren);

´ Can someone point out what is wrong here?

like image 940
Carsten Løvbo Andersen Avatar asked Mar 03 '23 22:03

Carsten Løvbo Andersen


2 Answers

I found out that if I do this then it works.

var umbf = Umbraco.Web.Composing.Current.Factory.GetInstance<IUmbracoContextFactory>();
using (var contextf = umbf.EnsureUmbracoContext())
{
    var umbcontext = contextf.UmbracoContext;
    IContentService cs = Umbraco.Core.Composing.Current.Services.ContentService;
    cs.SaveAndPublish(child);

}
like image 129
Carsten Løvbo Andersen Avatar answered May 10 '23 20:05

Carsten Løvbo Andersen


I believe you're getting your ContentService the wrong way and therefore it may be empty, causing a null reference exception.

If you're in a SurfaceController, you can get ContentService like this:

var cs = Services.ContentService;

If you're in a class where Services is not exposed, you can get it like this:

var cs = ApplicationContext.Current.Services.ContentService;

Read more about it in Umbracos documentation below :)

https://our.umbraco.com/documentation/Reference/Management/Services/ContentService/

like image 38
Mikkel Avatar answered May 10 '23 18:05

Mikkel