1

我正在尝试将对象展平为视图模型。这些是类:

public class Customer
{
    public virtual string Company { get; set; }
    public virtual string Name { get; set; }
    public virtual Address DestinationAddress { get; set; }
}

public class Address
{
    public virtual string Street { get; set; }
    public virtual string City { get; set; }
    public virtual string Province { get; set; }
    public virtual string State { get; set; }
    public virtual string PostCode { get; set; }
    public virtual string Country { get; set; }
}

public class CustomerViewModel
{
    public string Company { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string Province { get; set; }
    public string State { get; set; }
    public string PostCode { get; set; }
    public string Country { get; set; }
}

该对象Customer使用 nHibernate 加载,有时Address(destination) 为空,因为数据库中没有关联。

我注意到映射非常缓慢,所以我下载了代码并进行了一些调试。我注意到空属性或对象抛出异常(NullReferenceException),所以我改变了我的映射做这样的事情:

.ForMember(dest => dest.DestinationCity, opt => opt.MapFrom(source => (source.DestinationAddress == null || source.DestinationAddress.City == null) ? string.Empty : source.DestinationAddress.City))
.ForMember(dest => dest.DestinationStreet, opt => opt.MapFrom(source => (source.DestinationAddress == null || source.DestinationAddress.Street == null) ? string.Empty : source.DestinationAddress.Street))
.ForMember(dest => dest.DestinationPostCode, opt => opt.MapFrom(source => (source.DestinationAddress == null || source.DestinationAddress.PostCode == null) ? string.Empty : source.DestinationAddress.PostCode))
.ForMember(dest => dest.DestinationCountry, opt => opt.MapFrom(source => (source.DestinationAddress == null || source.DestinationAddress.Country == null) ? string.Empty : source.DestinationAddress.Country))
.ForMember(dest => dest.DestinationProvince, opt => opt.MapFrom(source => (source.DestinationAddress == null || source.DestinationAddress.Province == null) ? string.Empty : source.DestinationAddress.Province))
.ForMember(dest => dest.DestinationState, opt => opt.MapFrom(source => (source.DestinationAddress == null || source.DestinationAddress.State == null) ? string.Empty : source.DestinationAddress.State))

有了这个解决方案,一切正常,但我认为它不是特别“优雅”。我注意到的另一件事是,当我用空地址加载客户时——出于某种奇怪的原因——与设置了地址的对象相比,它仍然很慢。

我想知道是否有更好的选择。

PS:

我试图衡量表现。完全加载的对象平均需要00:00:00.0003993才能加载。具有一些空属性的对象平均需要00:00:04.5745887

4

0 回答 0