C# + Entity Framework – Generate Running Number ID for Different Module from the System

C# + Entity Framework – Generate Running Number ID for Different Module from the System

 
   CREATE TABLE [dbo].[RunningNum](
      [Num_ID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
      [Num_ModuleName] [nvarchar](30) NOT NULL DEFAULT(''),
      [Num_ModuleDesc] [nvarchar](max) NOT NULL DEFAULT(''),
      [Num_ModuleID] [int] NOT NULL,
      [Num_ModuleYear] [nvarchar](4) NOT NULL,
      [UpdatedBy] [nvarchar](30) NOT NULL DEFAULT(''),
      [UpdatedDate] [datetime] NOT NULL
   )
 
 
   public int getID(string ModuleName, string ModuleDesc, string ExecutionBy)
   {
      int ID = 0;
      int Num_ModuleYear = System.DateTime.Now.Year;
      RunningNum item = null;
 
      using (var dbContextTransaction = this.context.Database.BeginTransaction())
      {
         item = context.RunningNums
                    .Where(r => r.Num_ModuleName == ModuleName && r.Num_ModuleYear == Num_ModuleYear.ToString())
                    .FirstOrDefault();
 
         if (item != null)
         {
            item.Num_ModuleID = item.Num_ModuleID + 1;
            item.UpdatedBy = ExecutionBy;
            item.UpdatedDate = System.DateTime.Now;
 
            ID = item.Num_ModuleID;
         }
         else
         {
            item = new RunningNum();
 
            item.Num_ModuleID = 1;
            item.Num_ModuleName = ModuleName;
            item.Num_ModuleDesc = ModuleDesc;
            item.Num_ModuleYear = Num_ModuleYear.ToString();
            item.UpdatedBy = ExecutionBy;
            item.UpdatedDate = System.DateTime.Now;
 
            ID = item.Num_ModuleID;
 
            context.RunningNums.Add(item);
         }
 
         context.SaveChanges();
         dbContextTransaction.Commit();
      }
 
      return ID;
   }