'EF generate a value of a property that is based from Identity Id

I have this model and what I want to do is to is to generate a value for RefNumber that based it from the Id. Example value is if the data stored has an Id of 1, the reference number should be XYZ001 where the first 3 letters are just random and 001 is just the id plus a padded left zeros.

public class Receipt: BaseModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string RefNumber { get; set; }
}

I want to avoid this kind of logic where I manually set the RefNumber and call SaveChanges again like below:

var receipt = new Receipt()
database.Receipts.Add(receipt)
await database.SaveChangesAsync(cancellation).ConfigureAwait(false);

// I don't want to do this
receipt.RefNumber = GenerateRefNumber(receipt.Id)
await database.SaveChangesAsync(cancellation).ConfigureAwait(false);

Is there a better way in doing this? I want to do this on first SaveChanges but I don't know how.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source