0

I am trying to CREATE or UPDATE multiple Payment for a single Order. I would like to update the record if it exists in the database(Primary Key Value is not the default value), and I would like the record to be created if it doesn't exist in the database. For the moment, when I'm doing the creation, the Mapping adds a new order, by Payment, adds a necessary Lines and also adds the Product Item and the Wallet even if they already exist.

I use the ReverseMap() in all the DTO objects. here is an illustration

conf.CreateMap<Payment, PaymentDTO>()
            .ForMember(dest => dest.Amount, opt => opt.MapFrom(src => src.Amount))
            .ForMember(dest => dest.C_Order, opt => opt.MapFrom(src => src.C_Order))
            .ForMember(dest => dest.C_Wallet, opt => opt.MapFrom(src => src.C_Wallet))
            .ForMember(dest => dest.DateOf, opt => opt.MapFrom(src => src.DateOf))
            .ForMember(dest => dest.ID, opt => opt.MapFrom(src => src.ID))
            .ForMember(dest => dest.Order, opt => opt.MapFrom(src => src.Billing_Invoice))
            .ForMember(dest => dest.Wallet, opt => opt.MapFrom(src => src.CashWallet))
           .ReverseMap();

same logic is implement in OrderDTO, WalletDTO and so on. How to tell AutoMapper not to create new record when this record do exists in the database ? in the controller action, I tried to attach children to the context as follow _context.Wallets.Attach(model.wallet); but nothing seems to be working

here is the database diagramdigram

Bellash
  • 7,560
  • 6
  • 53
  • 86

1 Answers1

0

For the entities that exist in the database, either Attach() them to the DbContext, or set their State to Unchanged.

See Entity Framework Add and Attach and Entity States

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67