1

我正在使用 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);

这工作正常,除了 aPerson没有a 的情况Office,在这种情况下,LEFT JOINsql 查询的结果为 Office、Address 和 Organization 列返回 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()

有没有办法处理这种情况?还是我必须求助于扁平对象或单独的数据库调用?

4

2 回答 2

3

这已在 NPoco 2.2.40 中修复。
感谢您报告它。

于 2013-09-25T23:56:28.157 回答
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
{
}
于 2013-09-24T16:57:41.290 回答