如何处理可能为空的嵌套 NPoco 对象
本文关键字:嵌套 对象 NPoco 何处理 处理 | 更新日期: 2023-09-27 18:32:32
我正在使用NPoco从我的数据库进行对象映射。我有以下实体:
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
{
}
并且我正在使用存储库中的NPoco检索对象:
var people = Context.Fetch<Person, Office, Address, Organisation>(sql);
这工作正常,除了Person
没有Office
的情况,在这种情况下,sql 查询中LEFT JOIN
的结果为"办公室"、"地址"和"组织"列返回 null。
在这种情况下,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()
有没有办法处理这种情况?还是必须求助于平展对象或单独的数据库调用?
这已在 NPoco 2.2.40 中修复。
感谢您举报。
尝试创建一个构造函数来初始化对象:
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
{
}