Search code examples
c#entity-frameworkef-code-first

Generate an unique string for a field in a pre-defined pattern when save using Code First Approch: Entity Framework


I have a table called Quotations and it has an unique string field called QuotationNo.

public class Quotation
{
    [Key]
    public int Id { get; set; } //PK
    public string QuotationNo{ get; set; } // Pattern QUOT/12-22/00001 => QUOT + MONTH-YEAR + PrimaryKey.ToStrin("5d");
}

So I have implemented it by calling _db.SaveChanges() method twice as follows.

if (ModelState.IsValid)
{
     _db.Quotations.Add(quot);
     _db.SaveChanges(); // 1 time saving
    
     quot.QuotationNo= "QUOT/" + DateTime.Today.ToString("dd-MM/") + quot.Id.ToString("D5");
     _db.Quotations.Update(quot);
     _db.SaveChanges(); // 2 time saving
}

Is there a short way to do this?


Solution

  • I found this method is more clear.

    Step 1: Creating new field in the table to store DateCreated.

    Step 2: Making QuotationNo a virtual and NotMapped field, which is always a calculated/generated field.

    See the code

    public class Quotation
    {
        [Key]
        public int Id { get; set; } //PK
        [Required]
        public DateTime DateCreated { get; set; } //New field to store quotation created date.
        [NotMapped]
        public virtual string? QuotationNo  //Ax Key(Quotation No: QUOT/01-22/0000001=> PQTN/mmYY/0000000)
        {
             get
             {
                 return $"QUOT/{this.DateCreated:dd-MM/}{PolyCostingId:D5}"; 
             }
             set
             {
                 this.PolyCostingCode = value;
             }
        }
    }