Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate db.DaysPastDue from DateTime.Now - db.Loan.DueDate in Controller

I need to calculate the daysPastDue in my application which will be calculated by DateTime.Now - Loan.DueDate.

An example would be: Loan.DueDate = 2/1/18 12:00:00 DateTime.Now = 2/4/18 2:17:00 DaysPastDue = Should be '3'

I can do this from my view by doing the following:

View

@if (DateTime.Now > item.Loan.DueDate)
{    
     item.Loan.DaysPastDue = (DateTime.Now - item.Loan.DueDate).Value.Days;
}

But the problem here is that it never saves in my database it just calculates on the view.

So I wanted to calculate the Loan.DaysPastDue value and do a db.SaveChanges() before I display the view.

How do I accomplish this?

Edit: Here is my update/insert method:

    // GET: Kits
            [Authorize(Roles = "Admin, User")]
            public ActionResult Index()
            {
                var kits = db.Kits.Include(k => k.Loan).Include(k => k.Products); 

//Right here is where I wanted to do something like:
// if (DateTime.Now > db.Loan.DueDate)
//{
//      var daysPastDue = (DateTime.Now - item.Loan.DueDate).Value.Days;
//      Loan.DaysPastDue = daysPastDue;
//      db.SaveChanges(Loan.DaysPastDue) //This is the part I think I'm stuck on            
   return View(kits.ToList());
        }
like image 670
Tim Avatar asked Jan 01 '26 09:01

Tim


1 Answers

You usually don't want to save a calculated value in the database. In your sample, it's 3 days past due now. Tomorrow it's 4 days. The view will show 4 days because it's calculating it, but how will the database value get updated if someone doesn't pull up that view?

If you still want to recompute and save that value when the view is shown, something like this should work:

foreach(var kit in kits.Where(k => DateTime.Now > k.Loan.DueDate)
{
    kit.Loan.DaysPastDue = (DateTime.Now - kit.Loan.DueDate).Value.Days;
    db.SaveChanges(kit);
}
like image 98
Joe Wilson Avatar answered Jan 02 '26 23:01

Joe Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!