实体映射问题

时间:2018-06-25 17:55:28

标签: asp.net automapper

触发帖子后,不会保存用户的名字和姓氏。我有一个用户类,该类继承自identityuser类,并且已在代码片段中声明了两个属性,分别是名字和姓氏。但是问题是,当我将帖子添加到仓库中时,它不会保存用户名,而是显示空值,这会引发异常。

我不知道如何映射,以便将用户名保存在数据库中。

 public abstract class AuditableEntity
 {
            [Required]
            public string Title { get; set; }
            [Required]
            public string Description { get; set; }
            public DateTime PostCreatedDate { get; set; }
            [Required]
            public User User { get; set; }  
        }

   public class TechPost : AuditableEntity
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }


    }   

    public class User : IdentityUser
    {
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }


    }
    public class TechPostCreation
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public DateTime PostCreatedDate { get; set; }
        public string Description { get; set; }
    }

    [HttpPost()]
    public IActionResult CreatePost([FromBody] TechPostCreation techCreatePost)
    {
        if (techCreatePost == null)
        {
            return BadRequest();
        }
        var techPostEntity = _mapper.Map<TechPost>(techCreatePost);
        _repo.AddTechBlogPost(techPostEntity);

        if (!_repo.Save())
        {
            return StatusCode(500, "A problem happend and could handle your request");
        }

        var techPostReturn = _mapper.Map<TechPostViewModel>(techPostEntity);

        return CreatedAtRoute("GetTechPost", new { id = techPostReturn.Id },
                techPostReturn);

    }

    public RepoMapping()
    {
        CreateMap<TechPost, TechPostViewModel>()
                 .ForMember(dest => dest.Name, opt => opt.MapFrom(src =>
                   $"{src.User.FirstName} {src.User.LastName}"));

        CreateMap<TravelPost, TravelPostViewModel>()
               .ForMember(dest => dest.Name, opt => opt.MapFrom(src =>
                   $"{src.User.FirstName} {src.User.LastName}"));

        CreateMap<TechPostCreation, TechPost>();

    }

1 个答案:

答案 0 :(得分:0)

此行:

var techPostEntity = _mapper.Map<TechPost>(techCreatePost);

使用此地图:

CreateMap<TechPostCreation, TechPost>();

由于您的User类是TechPost的子类,因此需要MapFrom子句。相反,您可以将字段重命名为UserFirstName / UserLastName,这样约定就可以生效了。

更改地图:

CreateMap<TechPostCreation, TechPost>()
    .ForMember(dest => dest.User.FirstName, opt => opt.MapFrom(src => src.FirstName))
    .ForMember(dest => dest.User.LastName, opt => opt.MapFrom(src => src.LastName));

此外,我不确定您的仓库正在做什么,但是您可能需要在过程中的某个时刻使用UserManager检索或创建User