0

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?

Lakshitha Kanchana
  • 844
  • 2
  • 12
  • 32

2 Answers2

1

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;
         }
    }
}
Lakshitha Kanchana
  • 844
  • 2
  • 12
  • 32
0

Please try this

public class Quotation
{
    public int Id { get; set; } //PK
    public string QuotationNo
            {
                get
                {
                    return string.IsNullOrWhiteSpace(this.QuotationNo)
                       ? $"QUOT/{DateTime.Today:dd-MM:hh:mm:ss/}{Id:D7}"
                       : this.QuotationNo;
                }

                set { this.QuotationNo = value; }
            }}

For example

var x = new Quotation();
x.Id = 12345;
var quotationNo = x.QuotationNo; 
// quotationNo will be QUOT/22-12/0012345

Some reference here Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

Lakshitha Kanchana
  • 844
  • 2
  • 12
  • 32
MichaelMao
  • 2,596
  • 2
  • 23
  • 54