I am not sure how to go about this. My ticket object, has a DateTime property called TicketCreationTime, which said property is defaulting to 1/1/0001 at 12 AM; every time it's edit entity function is called from the tickets controller.
How could I make it, so that the TicketCreationTime stays the same as changes are made to it's ticket object? That way, the creation time is always the time as when the ticket was made?
Ticket Object
public class Ticket
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime TicketCreationTime { get; set; }
public DateTime DueDate { get; set; }
public DateTime TicketUpdatedTime { get; set; }
public Ticket()
{
}
}
TicketsController Create
public async Task<IActionResult> Create([Bind("ID,Name,Description,TicketCreationTime,DueDate,TicketUpdatedTime,CurrentStatus,Importance")] Ticket ticket)
{
if (ModelState.IsValid)
{
DateTime StartTime = DateTime.Now;
ticket.TicketCreationTime = StartTime;
ticket.TicketUpdatedTime = StartTime;
_context.Add(ticket);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(ticket);
}
TicketsController Edit
public async Task<IActionResult> Edit(int id, [Bind("ID,Name,Description,TicketCreationTime,DueDate,TicketUpdatedTime,CurrentStatus,Importance")] Ticket ticket)
{
if (id != ticket.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
ticket.TicketUpdatedTime = DateTime.Now;
_context.Update(ticket);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TicketExists(ticket.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(ticket);
}
CodePudding user response:
Use DateTime?
instead of DateTime
for TicketCreationTime. And update it if it is null:
ticket.TicketUpdatedTime = DateTime.Now;
if (ticket.TicketCreationTime is null)
{
ticket.TicketCreationTime = ticket.TicketUpdatedTime;
}
CodePudding user response:
You could change the property to use a private setter and initialize it in the constructor of your Ticket
class:
public class Ticket
{
// other properties ...
public DateTime TicketCreationTime { get; private set; }
public Ticket()
{
if (TicketCreationTime == DateTime.MinValue)
TicketCreationTime = DateTime.Now;
}
}
And don't try to update it in the Create
method.
Changing to use a private setter means the value can only set from within the Ticket
class, so other classes won't be able modify it's value, which sounds like the behaviour you want.