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?
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);
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With