【问题标题】:How to map object Id from DTO to existing object in database?如何将对象 ID 从 DTO 映射到数据库中的现有对象?
【发布时间】:2023-03-15 18:41:01
【问题描述】:

我正在尝试使用 automapper 和 EF 核心将对象 ID 映射到现有对象。 我的 dto 仅接受 LocationId,但如果数据库中存在具有此类 ID 的对象,我想在 WorkRecord 实体中映射完整的 Location 对象,否则控制器将返回 BadRequest

DTO:

    public class WorkRecordCreateDto
    {
        [Required]
        public int? LocationId { get; set; }
    }

型号

    public class WorkRecord
    {
        public int Id { get; set; }
        public Location Location { get; set; }
    }

控制器:

        [HttpPost]
        public ActionResult Post(WorkRecordCreateDto workRecordDto)
        {
            var workRecord = _mapper.Map<WorkRecord>(workRecordDto);
            _repository.GetRepository<WorkRecord>().Add(workRecord);
            _repository.SaveChanges();
            return Ok();

        }

【问题讨论】:

    标签: c# asp.net-core .net-core entity-framework-core automapper


    【解决方案1】:

    为此我们有一个 EnityConverter:

    public class EntityConverter<TDestination> : IValueConverter<int, TDestination>
    {
        private readonly ISession session;
    
        public EntityConverter(ISession session)
        {
            this.session = session;
        }
    
        public TDestination Convert(int sourceMember, ResolutionContext context)
        {
            return session.Get<TDestination>(sourceMember);
        }
    }
    

    要使用它,您必须配置映射器,使其可以使用 DependencyInjection。我们使用 Grace,它会在您的环境中有所不同:

    container.Configure(c => c.ExportFuncWithContext<IMapper>((scope, staticContext, context)
                        => new Mapper(automapperConfig, t => scope.Locate(t))).Lifestyle.SingletonPerScope());
    

    现在您可以在 AutoMapper 映射中添加 EntityConverter:

    CreateMap<WorkRecord, WorkRecordCreateDto>()
                .ReverseMap()
                .ForMember(d => d.Location, opts => opts.ConvertUsing<EntityConverter<WorkRecord>, int>(src => src.LocationId));
    

    【讨论】:

      猜你喜欢
      • 2011-11-30
      • 1970-01-01
      • 2023-04-03
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 2022-10-22
      • 1970-01-01
      相关资源
      最近更新 更多