Home > Back-end >  ASP.NET Core Web API - How to store combination of attributes as raw data into a single column of an
ASP.NET Core Web API - How to store combination of attributes as raw data into a single column of an

Time:11-24

I am using ASP.NET Core Web API. I have these models:

public abstract class EntityBase
{
    [Key]
    public int Id { get; set; }
}

public class Mandate : EntityBase
{
    public DateTime DueDate { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public virtual TransactionLog TransactionLog { get; set; }
}

public class TransactionLog
{
    [Key, ForeignKey("Mandate")]
    public int? MandateId { get; set; }

    public string RawData { get; set; }
    public virtual Mandate Mandate { get; set; }
}

Models: Mandate and TransactionLog

Mandate has one-to-one relationship with TransactionLog

Mandate Table

  • Id
  • DueDate
  • StartDate
  • EndDate

TransactionLog

  • MandateId (Key)
  • RawData

ViewModel (Dto):

public class MandateDto
{
    public DateTime DueDate { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int? MandateId { get; set; }
    public string? RawData { get; set; }
}

EntityMapper:

public class EntityMapper
{
    public Mandate FromMandateDtoToMandate(MandateDto mandate)
    {
        return new Mandate
        {
            DueDate = mandate.DueDate,
            StartDate = mandate.StartDate,
            EndDate = mandate.EndDate
        };
    }

    public TransactionLog FromMandateDtoToTransactionLog(MandateDto mandate)
    {
        return new TransactionLog
        {
            RawData = ???,
        };
    }
}

MandateService:

    public async Task<Mandate> Post(MandateDto mandate)
    {
        var mapper = new EntityMapper();
        var mandate = mapper.FromMandateDtoToMandate(mandate);
        var transaction = mapper.FromMandateDtoToTransactionLog(mandate);

        try
        {
            await _unitOfWork.MandateRepository.Insert(mandate);
            await _unitOfWork.TransactionRepository.Insert(transaction);
            await _unitOfWork.SaveChangesAsync();
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }

        return mandate;
        return transaction;
    }

As explained earlier, Mandate has one-to-one relationship with TransactionLog. Since both Mandate and TransactionLog Data will be inserted at the same time, I want to automatically insert DueDate,StartDate, EndDate fron Mandate into RawData of TransactionLog as JSON RawData:

RawData = ???

How do I achieve this?

Thanks

CodePudding user response:

You can use the JsonSerializer.Serialize method from System.Text.Json to do that.

You can read this for more info

  • Related