Base solution for your next web application
Open Closed

Get object id after insert #4608


User avatar
0
bakinalp created

Hi guys,

I'm totallay new to the the aspnetzero and angular so please bear with me.

My objective is to create a procurement request form. Form has some generic fields and 2 areas where user can add products and invitees to the request.

Project type: Angular/Core I have 3 objects as follows: PEvent PEventProduct (Contains PEventID, ProductID, and fields like quantity required) PEventInvitee Product

I have no problems saving the initial Pevent Object but once inserted I need to get the object immediatly so that I can save products and invitees associated to it as well. Below code works for the first part where I insert the pevent. But it fails on second part stating EventId must be between 1 and 2147483647 I believe the problem will be solved if I can get the inserted objects eventid and pass it to neweventproduct.eventid.

The question is whether it is possible to get the resulting object after insert operation.

save(): void {
        this._procurementService.createPEvent(this.pevent)
                .finally(() => this.saving = false)
                .subscribe(() => {
                           this.notify.info(this.l('SavedSuccessfully'));              
               });
//works  up to here without a problem 
        
        //this.newEventProduct.EventId = <- Pass EventID here from the result
        this._procurementService.addEventProduct(this.newEventProduct).subscribe(
                  result => {
                     this.editingPevent.eventProducts.push(result);
                     this.newEventProduct.quantity = 1;
                     this.notify.success(this.l('SavedSuccessfully'))
                 });
//errors here stating EventId must be between 1 and 2147483647 
}

13 Answer(s)
  • User Avatar
    0
    aaron created
    Support Team
    this._procurementService.createPEvent(this.pevent)
        .then(result => {
            this.newEventProduct.EventId = result.Id;
            this._procurementService.addEventProduct(this.newEventProduct).subscribe(
                result => {
                    this.editingPevent.eventProducts.push(result);
                    this.newEventProduct.quantity = 1;
                    this.notify.success(this.l('SavedSuccessfully'))
                });
        })
        .finally(() => this.saving = false)
        .subscribe(() => {
            this.notify.info(this.l('SavedSuccessfully'));              
        });
    
  • User Avatar
    0
    bakinalp created

    Thank you aaron for your response I was away for a few days. ( my wife was in labor and I took a few days off :D ).

    I have tested out the .then statement but it is throwing an error saying "then does not exist on type 'Observable <void>' "

    I have imported import { Observable } from 'rxjs/Observable'; but this does not resolve the problem. Am I missing something?

  • User Avatar
    0
    aaron created
    Support Team

    my wife was in labor and I took a few days off :D

    Congrats!

    I have tested out the .then statement but it is throwing an error saying "then does not exist on type 'Observable <void>' "

    Misconception on my part. This should work:

    this._procurementService.createPEvent(this.pevent)
        .finally(() => this.saving = false)
        .subscribe(event => {
            this.notify.info(this.l('SavedSuccessfully'));
    
            this.newEventProduct.EventId = event.Id;
            this._procurementService.addEventProduct(this.newEventProduct).subscribe(
                result => {
                    this.editingPevent.eventProducts.push(result);
                    this.newEventProduct.quantity = 1;
                    this.notify.success(this.l('SavedSuccessfully'))
                });
        });
    
  • User Avatar
    0
    bakinalp created

    Thanks Aaron ,

    after subscribe I have tried to check the event value using a simple alert but it shows null. The value is submitted to the database fine but still cant get the eventid. I'm probably missing something simple but no idea what.

    alert(event); //returns null
            alert(event.Id); //returns null
            this.newEventProduct.EventId = event.Id;
    
  • User Avatar
    0
    aaron created
    Support Team

    Can you check the response in the Network tab of your browser's developer console?

  • User Avatar
    0
    bakinalp created

    post looks succesfull but response is null. Shall I look somewhere else? I am trying to achieve this on autogenerated edit-or-create-modal.ts

  • User Avatar
    0
    aaron created
    Support Team

    Can you show the code for CreateOrEdit?

  • User Avatar
    0
    bakinalp created

    Here is the code in ts.

    import { Component, ViewChild, Injector, Output, EventEmitter} from '@angular/core';
    import { ModalDirective } from 'ngx-bootstrap';
    import { ProcurementServiceProxy, CreateOrEditPEventDto} from '@shared/service-proxies/service-proxies';
    import { AppComponentBase } from '@shared/common/app-component-base';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/fromPromise';
    import 'rxjs/add/operator/toPromise';
    
    @Component({
        selector: 'createOrEditPEventModal',
        templateUrl: './create-or-edit-pEvent-modal.component.html'
    })
    export class CreateOrEditPEventModalComponent extends AppComponentBase {
    
        @ViewChild('createOrEditModal') modal: ModalDirective;
    
        @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    
        active = false;
        saving = false;
       
        pEvent: CreateOrEditPEventDto = new CreateOrEditPEventDto();
    
        constructor(
            injector: Injector,
            private _procurementServiceProxy: ProcurementServiceProxy
        ) {
            super(injector);
        }
    
        ngOnInit(): void {
            
        }
    
        show(pEventId?: number): void {
            if (!pEventId) { 
    			this.pEvent = new CreateOrEditPEventDto();
    			this.pEvent.id = pEventId;
    			this.active = true;
    			this.modal.show();
            }
    		else{
    			this._procurementServiceProxy.getPEventForEdit(pEventId).subscribe(pEventResult => {
    				this.pEvent = pEventResult;
    				this.active = true;
    				this.modal.show();
    			});
            }
            
        }
    
        save(): void {
    		/*	this.saving = true;
    			this._procurementServiceProxy.createOrEdit(this.pEvent)
    			 .finally(() => { this.saving = false; })
    			 .subscribe(() => {
    			    this.notify.info(this.l('SavedSuccessfully'));
    				this.close();
    				this.modalSave.emit(null);
                    });
            */
            this._procurementServiceProxy.createOrEdit(this.pEvent)
                .finally(() => this.saving = false)
                .subscribe(event => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    alert(event);                
                });
        }
    
        close(): void {
            this.active = false;
            this.modal.hide();
        }
    }
    
  • User Avatar
    0
    aaron created
    Support Team

    How about the server-side code?

  • User Avatar
    0
    bakinalp created
    using System;
    using System.Linq;
    using System.Linq.Dynamic.Core;
    using Abp.Linq.Extensions;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Abp.Domain.Repositories;
    using Procure.Procurement.Dtos;
    using Abp.Application.Services.Dto;
    using Procure.Authorization;
    using Abp.Authorization;
    using Microsoft.EntityFrameworkCore;
    
    namespace Procure.Procurement
    {
    	[AbpAuthorize(AppPermissions.Pages_Procurement)]
        public class ProcurementAppService : ProcureAppServiceBase, IProcurementAppService
        {
    		 private readonly IRepository<PEvent> _pEventRepository;
    
    		  public ProcurementAppService(IRepository<PEvent> pEventRepository) 
    		  {
    			_pEventRepository = pEventRepository;
    		  }
    
    		 public async Task<PagedResultDto<PEventDto>> GetAll(GetAllPEventsInput input)
             {
                var query = _pEventRepository.GetAll().WhereIf(
                        !string.IsNullOrWhiteSpace(input.Filter),
                        e =>  e.Title.Contains(input.Filter) || e.Description.Contains(input.Filter) 
                    );
    
                var totalCount = await query.CountAsync();
    
                var pEvents = await query
                    .OrderBy(input.Sorting ?? "id asc")
                    .PageBy(input)
                    .ToListAsync();
    
                return new PagedResultDto<PEventDto>(
                    totalCount,
                    ObjectMapper.Map<List<PEventDto>>(pEvents)
                );
             }
    		 
    		 [AbpAuthorize(AppPermissions.Pages_Procurement_Edit)]
    		 public async Task<CreateOrEditPEventDto> GetPEventForEdit(EntityDto<int> input)
             {
                var pEvent = await _pEventRepository.FirstOrDefaultAsync(input.Id);
                return ObjectMapper.Map<CreateOrEditPEventDto>(pEvent);
             }
    
    		 public async Task CreateOrEdit(CreateOrEditPEventDto input)
             {
                if(input.Id == null){
    				await Create(input);
    			}
    			else{
    				await Update(input);
    			}
             }
    
    		 [AbpAuthorize(AppPermissions.Pages_Procurement_Create)]
    		 private async Task Create(CreateOrEditPEventDto input)
             {
                var pEvent = ObjectMapper.Map<PEvent>(input);
    
    			            if (AbpSession.TenantId != null)
                { 
     pEvent.TenantId =  (int) AbpSession.TenantId;
                }
    
                await _pEventRepository.InsertAsync(pEvent);
             }
    
    		 [AbpAuthorize(AppPermissions.Pages_Procurement_Edit)]
    		 private async Task Update(CreateOrEditPEventDto input)
             {
                var pEvent = await _pEventRepository.FirstOrDefaultAsync((int)input.Id);
                 ObjectMapper.Map(input, pEvent);
             }
    
    		 [AbpAuthorize(AppPermissions.Pages_Procurement_Delete)]
             public async Task Delete(EntityDto<int> input)
             {
                await _pEventRepository.DeleteAsync(input.Id);
             }
        }
    }
    
  • User Avatar
    0
    aaron created
    Support Team

    Well, you're not returning.

    public async Task<PEventDto> CreateOrEdit(CreateOrEditPEventDto input)
    {
        if (input.Id == null)
        {
            return await Create(input);
        }
        else
        {
            return await Update(input);
        }
    }
    
    private async Task<PEventDto> Create(CreateOrEditPEventDto input)
    {
        var pEvent = ObjectMapper.Map<PEvent>(input);
    
        if (AbpSession.TenantId.HasValue)
        {
            pEvent.TenantId = AbpSession.TenantId.Value;
        }
    
        await _pEventRepository.InsertAsync(pEvent);
    
        return ObjectMapper.Map<PEventDto>(pEvent);
    }
    
    private async Task<PEventDto> Update(CreateOrEditPEventDto input)
    {
        var pEvent = await _pEventRepository.FirstOrDefaultAsync(input.Id.Value);
        ObjectMapper.Map(input, pEvent);
    
        // ...
    }
    
  • User Avatar
    0
    bakinalp created

    Hi Aaron thanks for the support.

    Finally I can get a response when I create a record but the id field seems a bit odd. I am getting a negative number close to but not exactly int.MinValue . I think this is the temp id before record is saved to the db. İs this the expected behaviour?

  • User Avatar
    0
    aaron created
    Support Team

    Oh, you should inject IUnitOfWorkManager and call SaveChanges before mapping:

    private async Task<PEventDto> Create(CreateOrEditPEventDto input)
    {
        // ...
    
        await _pEventRepository.InsertAsync(pEvent);
    
        await _unitOfWorkManager.Current.SaveChangesAsync();
    
        return ObjectMapper.Map<PEventDto>(pEvent);
    }