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?

Upvotes: 5

Views: 1753

Answers (3)

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);

}

Upvotes: 5

Legion
Legion

Reputation: 791

Look that link, seems that Umbraco 'Save' works even if something is null but not completely:

Save is working but not completely, it is saving the content to the db but not to the Umbraco backoffice. And even when I try wrapping the setValues inside a

if (blogNode.HasProperty("title")) {

I still get a null reference error.

In the OP case he's taking the wrong contentService in the first step, so i think @Mikkel answer is not completely wrong:

Turns out I had used the wrong parentId in this line:

var newBlog = contentService.CreateContent(post.Title, 1053, "umbNewsItem", 0);

the correct statement was:

var newBlog = contentService.CreateContent(post.Title, 1061, "umbNewsItem", 0);

L-

Upvotes: 0

Mikkel
Mikkel

Reputation: 1865

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/

Upvotes: 4

Related Questions