展平空对象

时间:2013-10-24 12:41:51

标签: c# automapper

我正在尝试将对象展平为viewmodel。 这些是类:

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(目标)为null,因为数据库中没有关联。

我注意到映射速度很慢,所以我下载了代码并进行了一些调试。 我注意到null属性或对象抛出异常(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 的平均值。 具有某些null属性的对象的平均值为 00:00:04.5745887

0 个答案:

没有答案