Search code examples
2sxc

App.Data.Update throws object reference error when the entity to update has a reference to another entity


When I try to save a change in an entity I get an object reference error when using dynCode.App.Data.Update. I checked if all variables and elements in the data dictionary are available and that is the case. Code:

public void ProcessReOrder(string elementId, string order)
{
    var entityGuid = Guid.Parse(elementId);
    decimal orderNr = Convert.ToDecimal(order);
    var tabId = Dnn.Tab.TabID;
    var modId = Dnn.Module.ModuleID;
    var block = ToSic.Sxc.Dnn.Factory.CmsBlock(tabId, modId);
    var dynCode = ToSic.Sxc.Dnn.Factory.DynamicCode(block);
    var formElement = dynCode.AsList(dynCode.App.Data["FormElements"]).Where(x => x.EntityGuId == entityGuid).FirstOrDefault();
    var converter = new EntitiesToDictionary();
    var data = converter.Convert(AsEntity(formElement));
data["Order"] = orderNr;
    dynCode.App.Data.Update(formElement.EntityId, data); <-- Throws the error
}

It looks like it could be an issue when the FormElements entity has an link to another entity. When I create a small sample with just name (string) and order (number) as fields and send a webApi post with a new ordernumber it works without a problem.

How do I update an Entity with one or more references to other entities?

Update: issues is fixed using

Data["Form"] = new List<Guid>() { guid }

I found a second issue when you have empty field for field groups. When I have an empty field, I get the same object reference error.


Solution

  • Data references should be ID-pointers - either int or guid, as a list or array.

    So even if you're pointing to 1, make sure it's [1] or new List<int>() { 1 } or new List<Guid>() { guid}

    something like that.