如何在ASP.NET MVC5中为特定模式执行自动递增

问题描述 投票:1回答:1

在我的项目中,ID列自动加1,因此我需要为其创建自定义模式。

而不是:

1

2

3

...

我需要这个Ad-1-(mm)-(yy)

mm:当前月份(由两位数组成),yy:当前年份(由两位数字组成),

例如,如果我想在本月创建记录,则ID应该如下所示:

Ad-1-10-19(第一条记录)

Ad-2-10-19(第二条记录)

Ad-3-10-19(第3条记录).......

您能建议正确的方法吗?

sql asp.net-mvc entity-framework data-annotations ef-fluent-api
1个回答
1
投票

假设您仍要保留整数主键ID列。您可以添加一个void函数来设置该属性并在控制器内部调用它;

// your model
public class Product{

   [Key]
   public int productId {get;set;}

   public string code {get;set;}

   private void setCode() {
      this.code= "Ad-" + this.productId.ToString() + "-" + DateTime.Now.ToString("MM-yy");
   }
}

// your controller
public class ProductController : Controller(){
   public ActionResult CreateProduct(){
      Product p = new Product();
      product.setCode();
   }
}

或者您可以将其放入类的构造函数中,以便每次实例化对象时,都会自动创建该对象;

// your model
public class Product{

   // constructor
   public Product(){
      this.setCode();
   }

   [Key]
   public int productId {get;set;}

   public string code {get;set;}

   private void setCode() {
      this.code= "Ad-" + this.productId.ToString() + "-" + DateTime.Now.ToString("MM-yy");
   }
}

© www.soinside.com 2019 - 2024. All rights reserved.