Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring null references when de-serializing a massive XML document

I'm getting a massive payload of XML from my WCF service, and I need to write it into a SQL database. I'm using the latest version of .NET and Entity Framework 6.

"Okay, that's great," you may say, "but what's the question?"

Well, the XML is being deserialized into C# objects (generated from paste-special) and they're working just great. However, whenever the payload from the service does not contain some field, I get a null reference exception when I'm writing the XML object over to the EF object (This is a class method):

public ICollection<object> GetObjects()
{
    List<object> objs = new List<object>();

    foreach (var i in XmlObject.SubObj.SubObj.SubObj)
    {
        objs.Add(new MyEfObject() {
            Prop1 = XmlObject.SubObj.SubObj.SubObj.ObjProperty // If "ObjProperty" is null,
                                                               // I get a null reference exception
        });
    }

    return objs;
}

So, I have really inelegant code to check

if (!ReferenceEquals(XmlObject.SubObj.SubObj.SubObj.ObjProperty, null) {
    // Do stuff
}

This would normally be fine, but the object is so large and I want to avoid typing this 150+ times (and for all the object properties of the object).

There has to be a more elegant way, no?

like image 453
Ellis Avatar asked Nov 08 '22 23:11

Ellis


1 Answers

You may simply use == but IMO the inelegant part is not check for null (which may be avoided using null-object pattern) but the fact you're accessing XmlObject.SubObj.SubObj.SubObj.ObjProperty, I think your classes are really too coupled.

That said, if you can't change this, then you may use LINQ to make your code more readable:

public ICollection<MyEfObject> GetObjects() {
    return XmlObject.SubObj.SubObj.SubObj
        .Where(x => x.property != null)
        .Select(x => new MyEfObject { Prop1 = x.property })
        .ToList();
}
like image 146
Adriano Repetti Avatar answered Nov 15 '22 06:11

Adriano Repetti