context.SaveChanges()返回0;

时间:2019-07-18 14:47:53

标签: c# asp.net-core entity-framework-core

我正在尝试将JobLog的新实例保存到数据库。即使您添加了一个新的jobLog实例,context.SaveChanges()始终返回0。您似乎可以尝试对其进行控制台,并且始终返回0。

private readonly EntityContext context;
private TBCPaymentOptions _tbcPaymentOptions = null;

public AccountBilling(EntityContext _context) {
 context = _context;
}

public AccountBilling(EntityContext _context, IOptions < TBCPaymentOptions > tbcPaymentOptions) {
 context = _context;
 this._tbcPaymentOptions = tbcPaymentOptions.Value;

}

public void Save() {
 try {
  context.SaveChanges();

 } catch (Exception e) {
  Console.WriteLine(e);
  throw;
 }

}

public void CalculateUserCharge(DateTime date) {
 var latestJob = context.JobLogs.OrderByDescending(c => c.StartDate).Where(c => c.JobId == (int) JobEnum.CloseDay).FirstOrDefault();
 var jobLog = new JobLog();

 if (latestJob != null && latestJob.JobStatusID == (int) JobStatusEnum.Active) {
  jobLog.JobStatus.Id = (int) JobStatusEnum.Canceled;
  jobLog.EndDate = DateTime.Now;
  //this.Save();
  context.SaveChanges();
  if (context.SaveChanges() > 0) {
   Console.WriteLine("ok");
  } else {
   System.Console.WriteLine("NOPE");
  }
 } else {

  try {

   jobLog.JobId = (int) JobEnum.CloseDay;
   jobLog.JobStatusID = (int) JobStatusEnum.Active;
   jobLog.StartDate = DateTime.Now;
   // this.Save();
   context.SaveChanges();
   if (context.SaveChanges() > 0) {
    Console.WriteLine("ok2");
   } else {
    System.Console.WriteLine("2NOPE");
   }
   var result = new List < GetActiveUserPackagesForOpenBillingPeriodResult > ();

   using(var conn = new NpgsqlConnection(context.ConnectionString)) {
    conn.Open();

    using(var cmd = new NpgsqlCommand("\"GetActiveUserPackagesForOpenBillingPeriod\"", conn)) {

     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("somedate", DateTime.Today);

     var reader = cmd.ExecuteReader();

     string x = DBNull.Value.Equals(reader) ? " " : reader.ToString();

     if (x != null) {
      while (reader.Read()) {
       result.Add(
        new GetActiveUserPackagesForOpenBillingPeriodResult {
         Amount = (decimal) reader["Amount"],
          PackageID = (int) reader["PackageID"],
          UserID = (int) reader["UserID"],
          AccountID = (int) reader["AccountID"],
          UserPackageStartDate = (DateTime) reader["UserPackageStartDate"],
        }
       );
      }
     }
     conn.Close();
    }

    var groupByResults = result.GroupBy(c => c.AccountID).Select(a => new {
     accountId = a.Key,
      lines = a.ToList()
    });

    foreach(var group in groupByResults) {

     var transactionHeader = new TransactionHeader() {

      TransactionHeaderTypeID = (int) TransactionHeaderTypeEnum.Charge,
       Date = date,
       CorrectionDescription = null,
       AccountID = group.accountId
     };

     foreach(var lineItem in group.lines) {
      transactionHeader.TransactionLines.Add(new TransactionLine() {
       UserID = lineItem.UserID,
        PackageID = lineItem.PackageID,
        Amount = this.CalculateUserChargeMethod(date, lineItem.Amount, lineItem.UserPackageStartDate)
      });

     }

     transactionHeader.TotalAmount = transactionHeader.TransactionLines.Sum(c => c.Amount);

     this.context.TransactionHeaders.Add(transactionHeader);

     //this.Save ();
     context.SaveChanges();
     if (context.SaveChanges() > 0) {
      Console.WriteLine("3OK");
     } else {
      System.Console.WriteLine("3NOPE");
     }

    }
    jobLog.EndDate = DateTime.Now;
    jobLog.JobStatusID = (int) JobStatusEnum.Inactive;
    //this.Save();
    context.SaveChanges();

    ClosePeriodOnEndOfMonth(date, conn);
   }

  } catch (Exception ex) {
   jobLog.EndDate = DateTime.Now;
   jobLog.JobStatusID = (int) JobStatusEnum.Canceled;
   //this.Save();
   context.SaveChanges();
   if (context.SaveChanges() > 0) {
    Console.WriteLine("OK4");
   } else {
    System.Console.WriteLine("NOPE4");
   }

   //throw ex;
  }
 }
}

EntityContext上下文应该可以正常工作。这正是我在其余文件中初始化它的方式。私有只读EntityContext上下文;而不是将其放入构造函数中。

1 个答案:

答案 0 :(得分:3)

您正在创建一个新的JobLog实例,但从未将其添加到上下文中,即_context.Add(jobLog)。因此,当您致电_context.SaveChanges()时,EF认为没有任何事情要做,只是放弃了。 (返回值是执行的操作数,显然是零,因为没有任何事可做。)