Base solution for your next web application
Open Closed

How to insert depending data? #1515


User avatar
0
jamsecgmbh created

Hi, how can I insert data into two entities which depend on each other (Applicant has foreign key in JobApplication) and where the data is passed in one save action? I have tried to use "applicantId = _applicantRepository.InsertAndGetId(applicant);" to insert the Applicant first, get the ID of the entry and pass it to the method that inserts the JobApplication. I run into an error there. Could you please tell me how to do it right? Thank you!

public class JobApplicationAppService : JobApplicationDatabaseAppServiceBase, IJobApplicationAppService
{
	private readonly IRepository<JobApplication, long> _jobApplicationRepository;
	private readonly IRepository<Applicant, long> _applicantRepository;

	public JobApplicationAppService(IRepository<JobApplication, long> jobApplicationRepository, IRepository<Applicant, long> applicantRepository)
	{
		_jobApplicationRepository = jobApplicationRepository;
		_applicantRepository = applicantRepository;
	}

	public async Task CreateOrUpdateJobApplication(CreateOrUpdateJobApplicationInput input)
	{
		if (input.JobApplication.Id.HasValue)
		{
			// implement
		}
		else
		{
			var applicantId = CreateApplicant(input);
			CreateJobApplication(input, applicantId);
		}
	}

	[AbpAuthorize(AppPermissions.Pages_Tenant_JobApplications_CreateJobApplication)]
	protected virtual long CreateApplicant(CreateOrUpdateJobApplicationInput input)
	{
		long applicantId;
		// Create applicant first and then pass the new ID to the jobApplication
		var applicant = input.Applicant.MapTo<Applicant>();
		applicantId = _applicantRepository.InsertAndGetId(applicant);
		return applicantId;
	}		

	[AbpAuthorize(AppPermissions.Pages_Tenant_JobApplications_CreateJobApplication)]
	protected virtual void CreateJobApplication(CreateOrUpdateJobApplicationInput input, long applicantId)
	{
		input.Applicant.Id = applicantId;
		var jobApplication = input.Applicant.MapTo<Applicant>();
	}
}

2 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Seems like, you are doing it right. Can you share the error message ?

  • User Avatar
    0
    jamsecgmbh created

    You are right - it works, I am sorry - it was just bad database permission. Thank you very much!