Ignoring null references when de-serializing an XML document array

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

“Okay, that's great,” you can say, “but what is the question?”

Well, XML is deserialized into C # objects (generated from paste-special), and they work just fine. However, when the load from the service does not contain a field, I get an empty exception link when I write an XML object to an 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 is usually normal, but the object is so large, and I want to avoid entering this 150+ times (and for all properties of the object).

There should be a more elegant way, no?

+5
source share
1 answer

You can simply use == , but the IMO non-elegant part does not check null (which can be avoided with the null object template), but the fact that you are accessing XmlObject.SubObj.SubObj.SubObj.ObjProperty , I think your classes are really too connected.

However, if you cannot change this, you can 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(); } 
+1
source

Source: https://habr.com/ru/post/1239059/


All Articles