Home > Software engineering >  Generate an unique string for a field in a pre-defined pattern when save using Code First Approch: E
Generate an unique string for a field in a pre-defined pattern when save using Code First Approch: E

Time:12-22

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("D7");
     _db.Quotations.Update(quot);
     _db.SaveChanges(); // 2 time saving
}

Is there a short way to do this?

CodePudding user response:

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

  • Related