2015-11-20 1 views
0
public class CreateOrEditOwnerDetailInput : IInputDto 
    { 
     [Required] 
     public OwnerDetailEditDto OwnerDetail { get; set; } 
    } 

    [AutoMap(typeof(OwnerDetail))] 
    public class OwnerDetailEditDto 
    { 
     public const int MaxLength = 50; 
     public const int NotesMaxLength = 300; 

     public int? Id { get; set; } 

     [Required] 
     [MaxLength(MaxLength)] 
     public string LastName { get; set; } 


     [Required] 
     [MaxLength(MaxLength)] 
     public string CompanyName { get; set; } 

     [Required] 
     public OwnerContactDetailDto ContactDetail { get; set; } 

     [Required] 
     public AdditionalAddressDto AdditionalAddress { get; set; } 

    } 



[Table("IpOwnerDetails")] 
    public class OwnerDetail : FullAuditedEntity 
    { 
     public const int MaxLength = 50; 
     public const int NotesMaxLength = 300; 

     [Required] 
     [MaxLength(MaxLength)] 
     public virtual string LastName { get; set; } 

     [Required] 
     [MaxLength(MaxLength)] 
     public virtual string CompanyName { get; set; } 


     [ForeignKey("AdditionalAddressId")] 
     public virtual AdditionalAddress AdditionalAddress { get; set; } 
     public virtual int AdditionalAddressId { get; set; } 

     [ForeignKey("ContactDetailId")] 
     public virtual ContactDetail ContactDetail { get; set; } 
     public virtual int ContactDetailId { get; set; } 


    } 

public class OwnerContactDetailDto : FullAuditedEntityDto 
    { 
     public const int NumberMaxLength = 20; 

     [Required] 
     [MaxLength(NumberMaxLength)] 
     public string MainPhoneNumber { get; set; } 

     [MaxLength(NumberMaxLength)] 
     public string HomePhoneNumber { get; set; } 

     [Required] 
     public ContactDetailType Type { get; set; } 
    } 

    public class AdditionalAddressDto : FullAuditedEntityDto, IOutputDto 
    { 
     public const int MaxLength = 50; 

     [Required] 
     [MaxLength(MaxLength)] 
     public string StreetNumber { get; set; } 

     [Required] 
     public AddressType Type { get; set; } 

     [Required] 
     public int CityId { get; set; } 

     [Required] 
     public int StateId { get; set; } 


    } 

Mapper.CreateMap<AdditionalAddress, AdditionalAddressDto>() 
       .ReverseMap() 
       .ForMember(additionalAddress => additionalAddress.Id, options => options.Ignore()); 

      Mapper.CreateMap<ContactDetail, OwnerContactDetailDto>() 
       .ReverseMap() 
       .ForMember(contactDetail => contactDetail.Id, options => options.Ignore()); 


public async Task<int?> EditOwnerDetailAsync(CreateOrEditOwnerDetailInput input) 
     { 
      var ownerDetail = await _ownerDetailRepository.FirstOrDefaultAsync(p => p.Id == input.OwnerDetail.Id); 
      input.OwnerDetail.MapTo(ownerDetail);//after this it goes null 
      await _ownerDetailRepository.UpdateAsync(ownerDetail); 
      return input.OwnerDetail.Id; 

     } 

URL изображения:http://imgur.com/a/GRdw6После отображения Automapper, где объекты идут к нулю значения

Q: После отображения внутри EditOwnerDetailAsync метода, где оба AdditionalAddress и ContactDetail идет в null .Could вы сказать мне Зачем ? Пожалуйста, смотрите изображение для получения дополнительной информации.

Исключение:

ERROR 2015-11-20 17:56:18,666 [26 ] lers.Filters.AbpExceptionFilterAttribute - System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while 
updating the entries. See the inner exception for details. ---> 
System.Data.Entity.Core.UpdateException: An error occurred while updating the 
entries. See the inner exception for details. ---> 
System.Data.SqlClient.SqlException: The UPDATE statement conflicted with the 
FOREIGN KEY constraint 
"FK_dbo.IpOwnerDetails_dbo.IpAdditionalAddresses_AdditionalAddressId". The 
conflict occurred in database "IP", table "dbo.IpAdditionalAddresses", column 'Id'. 
    The statement has been terminated. 

Примечание: Странная вещь здесь, когда я приношу указатель отладки обратно в input.OwnerDetail.MapTo(ownerDetail); линии (2-й раз), то он заполняет данные для AdditionalAddress и ContactDetail объектов. Как это может произойти?

+0

Является ли метод «MapTo» расширением? Можете ли вы показать код в нем? – stuartd

+0

@stuartd Да, см. Этот документ..http: //www.aspnetboilerplate.com/Pages/Documents/Data-Transfer-Objects – Sampath

+0

Метод расширения [похоже, использует правильную перегрузку Карты (тот, который не перезаписать существующий объект)] (https://github.com/aspnetboilerplate/aspnetboilerplate/blob/master/src/Abp.AutoMapper/AutoMapper/AutoMapExtensions.cs), так что это не так. – stuartd

ответ

0

Сопоставления с AutoMapper выполнены либо по соглашению, либо по конфигурации. Для вложенных свойств, предположим, что у вас есть две вложенные свойства в качестве источника вашей карты, как

public class OuterSrc{ 
    public string Name {get;set;} 
    public InnerSrc Source{get; set;} 
} 
public class InnerSrc{ 
    public string Title{get; set;} 
} 

и назначения у вас есть один класс, как

public class Destination 
{ 
    public string Name{get; set;} 
    public string Title{get;set;} 
} 

Если определить отображение по умолчанию из OuterSrc в Destination будет Title Форма InnerSrc map to Title Недвижимость Destination. Простой ответ - нет, потому что свойства не названы в соответствии с соглашениями AutoMapper.
Так что в этом случае у меня есть пара вариантов. Во-первых, я могу изменить имя свойства, чтобы соответствовать конвенции как

public class Destination{ 
    public string Name{get;set;} // as earlier 
    public string SourceTitle{get;set;} // see the change here. Source is //property in `OuterSrc` and `Title` is property in `InnerSrc`. I just merged //them 
} 

Если вы думаете, это решение не является жизнеспособным, вы можете определить такие отображения в конфигурации, как

AutoMapper.Mapper.CreateMap<OuterSrc, Destination>() 
    .ForMember(dest => dest.Title, 
       opts => opts.MapFrom(src => src.Source.Title)); 

Делая это, ваш картографа будет знать, как отображать ваши внутренние свойства.

+0

Да, но по выше сценарию, где все одинаковы, нет? Почему все же это дает «null»? – Sampath

Смежные вопросы