我正在使用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
的结果为Office返回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()
有办法处理这种情况吗?或者我是否必须使用扁平化对象或单独的数据库调用?
答案 0 :(得分:3)
这已在NPoco 2.2.40中修复 感谢您报告。
答案 1 :(得分:0)
尝试创建构造函数来初始化对象:
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
{
}