This has been fixed in NPoco 2.2.40.
Thanks for reporting it.
How do I handle nested NPoco objects that may be null?
-
29-06-2022 - |
Domanda
I am using NPoco for object mapping from my database. I have the following entities:
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
{
}
and I am retrieving the objects using NPoco in my repository:
var people = Context.Fetch<Person, Office, Address, Organisation>(sql);
This is working fine, except for the case where a Person
does not have an Office
, in which case result of the LEFT JOIN
in the sql query returns null for the Office, Address and Organisation columns.
In this situation, an unhandled exception is thrown in NPoco:
System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation.
---> 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.<>c__DisplayClassa`1.<CreateMultiPocoFactory>b__9(IDataReader reader, Delegate arg3)
at NPoco.Database.<Query>d__14`1.MoveNext()
Is there a way to handle this situation? Or will I have to resort to a flattened object, or separate database calls?
Soluzione
Altri suggerimenti
Try creating a constructor to initialize objects:
public abstract class NamedEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Person : NamedEntity
{
public Person()
{
Office = new Office();
}
public Office Office { get; set; }
}
public class Office : NamedEntity
{
public Office()
{
Address = new Address();
ParentOrganisation = new Organisation();
}
public Address Address { get; set; }
public Organisation ParentOrganisation { get; set; }
}
public class Address
{
public string AddressLine1 { get; set; }
}
public class Organisation : NamedEntity
{
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow