Home > Enterprise >  ASP.NET Core Web API - How to post JSON Serialized data into the database
ASP.NET Core Web API - How to post JSON Serialized data into the database

Time:11-25

In ASP.NET Core Web API, I have:

public class LoanInfoVM
{
    [Required]
    public string LoanType { get; set; }
    [Required]
    public int LoanAmount { get; set; }
    [Required]
    public int Installments { get; set; }
    public string LoanData { get; set; }
}

EntityMapper:

public class EntityMapper
{
    public LoanInfo FromLoanInfoVMToLoan(LoanInfoVM loan)
    {
        LoanInfo loan = new LoanInfo()
        {
            LoanType = loan.LoanType,
            LoanAmount = loan.LoanAmount,
            Installments = loan.Installments,
        };

        string loanJsonData = JsonSerializer.Serialize(loan);
        return loan;
    }
}

LoanService:

    public async Task<LoanInfo> Post(LoanInfoVM loan)
    {
        var mapper = new EntityMapper();
        var loanDt = mapper.FromLoanInfovmToLoanInfo(loan);

        await _unitOfWork.LoanRepository.Insert(loanDt);
        await _unitOfWork.SaveChangesAsync();

        return loan;
    }

The model consists of LoanType, LoanAmount, Installments, LoanData.

LoanData is JsonSerializer for LoanType, LoanAmount, Installments.

I am only able to insert LoanType,LoanAmount,Installments.

But how do I include LoanData also which is JsonSerializer.Serialize(loan)?

I want to be able to do all these into the same model LoanInfo at the same submit.

Thanks

CodePudding user response:

In your mapper you could add

public class EntityMapper
{
    public LoanInfo FromLoanInfoVMToLoan(LoanInfoVM loan)
    {
        LoanInfo loan = new LoanInfo()
        {
            LoanType = loan.LoanType,
            LoanAmount = loan.LoanAmount,
            Installments = loan.Installments,
        };
        loan.LoanData = JsonSerializer.Serialize(loan)
        return loan;
    }
}

You have the variable loanJsonData but you never use it.

  • Related