Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I handle nested NPoco objects that may be null?
    primarykey
    data
    text
    <p>I am using NPoco for object mapping from my database. I have the following entities:</p> <pre><code>public abstract class NamedEntity { public int Id { get; set; } public string Name { get; set; } } public class Person : NamedEntity { public Office Office { get; set; } } public class Office : NamedEntity { public Address Address { get; set; } public Organisation ParentOrganisation { get; set; } } public class Address { public string AddressLine1 { get; set; } } public class Organisation : NamedEntity { } </code></pre> <p>and I am retrieving the objects using NPoco in my repository:</p> <pre><code>var people = Context.Fetch&lt;Person, Office, Address, Organisation&gt;(sql); </code></pre> <p>This is working fine, except for the case where a <code>Person</code> does not have an <code>Office</code>, in which case result of the <code>LEFT JOIN</code> in the sql query returns null for the Office, Address and Organisation columns.</p> <p>In this situation, an unhandled exception is thrown in NPoco:</p> <pre><code>System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---&gt; System.NullReferenceException: Object reference not set to an instance of an object. at poco_automapper(Person , Office , Address , Organisation ) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Delegate.DynamicInvokeImpl(Object[] args) at NPoco.MultiPocoFactory.CallCallback[TRet](Delegate callback, IDataReader dr, Int32 count) at NPoco.MultiPocoFactory.&lt;&gt;c__DisplayClassa`1.&lt;CreateMultiPocoFactory&gt;b__9(IDataReader reader, Delegate arg3) at NPoco.Database.&lt;Query&gt;d__14`1.MoveNext() </code></pre> <p>Is there a way to handle this situation? Or will I have to resort to a flattened object, or separate database calls?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload