hello devs am working on a asp.net project and I want to generate a product code dynamically,I don’t want to be adding it everytime,so I want the system to create it for me whenever I add a new Product.
here is my product class
public class Article
{
public Guid Id { get; set; }
public string ProductCode { get; set; }
public string Designation { get; set; }
public Guid FamilleId { get; set; }
public Guid EmballageGrosId { get; set; }
public Guid EmballageDetailId { get; set; }
public int StockMinimal { get; set; }
public int QuantiteDetail { get; set; }
public DateTime Created { get; set; } = DateTime.UtcNow;
public Famille Famille { get; set; }
public Emballage EmballageGros { get; set; }
public Emballage EmballageDetail { get; set; }
}
var currentYear = DateTime.Now.Year;
var productCode = $"001/{currentYear}";
var latestProduct = await context.products.OrderByDescending(f => f.Id)
.FirstOrDefaultAsync();
if (latestProduct != null && latestProduct.ProductCode.Contains(currentYear.ToString()))
{
var currentProduct = int.Parse(latestProduct.ProductCode.Split("/")[0]) + 1;
productCode = string.Format("{0:0000}/{1}", currentProduct, currentYear);
}
here am getting the ProductCode in this format 001/2023 where 2023 is the current Year but I need this format ART-001/2023
2
Answers
Please refer to string interpolation in C#. This gives multiple options to format the string and helps in text as per the needs.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
var productCode = $"ART- {ProductCode}/{currentYear}";
It’s always a good idea to separate the business logic code so it’s easier to test and understand. I would make a product code class like this:
The you can write unit tests to check it and write code like this: