2012-07-12 2 views
2

코멘트를 게시 한 사람이 게스트 인 경우, UserName이 User 테이블에서 채워지기 때문에 CommentUserViewModel이 올바르지 만 CommentUserViewModel은 null이지만 Comment 테이블에 게스트 이름이 저장된 CommentUserViewModel을 채우려면 어떻게해야합니까?AutoMapper로 null 객체를 채우는 방법?

public class CommentViewModel 
{ 
    public int Id { get; set; } 
    public CommentUserViewModel User { get; set; } 
} 

public class CommentUserViewModel 
{ 
    public string UserName { get; set; } 
    public string GuestName { get; set; } 
} 

내 매핑은 다음과 같습니다

Mapper.CreateMap<Comment, CommentViewModel>(); 
Mapper.CreateMap<User, CommentUserViewModel>(); 

(사용자의 속성을 검사 할 때 내가 널 예외를 공격하지 않는 한)에는 게스트 게시물이없는 경우이 작동합니다.

다음 매핑이 게스트에 대한 사용자 개체를 채우지 만 영향을 미치지 않는다고 생각했습니다. 게스트 이름도 비어있을 수 있으므로 null도 대체 할 수 있습니다.

Mapper.CreateMap<Comment, CommentUserViewModel>() 
.ForMember(c => c.GuestName, m => m.MapFrom(s => s.GuestName)) 
.ForMember(c => c.UserName, m => m.NullSubstitute("Guest")); 

매핑을 수정하여 User.GuestName을 채우는 방법은 무엇입니까?

편집

var comments = _repository.GetComment(); 
return Mapper.Map<IEnumerable<Comment>, IEnumerable<CommentViewModel>>(comments); 

그리고 내가 사용 엔티티 프레임 워크 :

public partial class Comment 
{ 
    public int Id { get; set; } 
    public string GuestName { get; set; } 

    public virtual User User { get; set; } 
} 

public partial class User 
{ 
    public string UserName { get; set; } 
} 
+0

그래서 당신은'Comment'를 매핑 할 ->'CommentUserViewModel', 당신은 명백한 calli입니까? 위의 두 가지 유형 사이에 Map()을 사용하거나'Comment' ->'CommentViewModel'에서 Map()을 호출하고 CommentUserViewModel 속성에 매핑하는 것에 대해 알고 싶습니까? 코드를 게시 할 수 있습니까? 나는 당신이 잘못 가고 있다고 생각하지만 확신 할 수 없다. – Charleh

+0

'Comment'와'User' 엔티티 클래스의 관련 코드를이 뷰 모델과 함께 게시하십시오. – danludwig

+0

나는 게시물을 업데이트했습니다. 감사합니다! – KevinUK

답변

0

이 게시물 도움 : AutoMapper Map Child Property that also has a map defined

Mapper.CreateMap<Comment, CommentUserViewModel>() 
      .ForMember(c => c.UserName, m => m.MapFrom(s => s.User.UserName)); 

Mapper.CreateMap<Comment, CommentViewModel>() 
      .ForMember(c => c.User, 
      opt => opt.MapFrom(s => Mapper.Map<Comment, CommentUserViewModel>(s))); 
관련 문제