Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC datetime list not saving

I have a simple MVC4 model that adds a DateTime.Now to a List<DateTime>() list.

However when I do an EntityState.Modified, the changes are not being kept. I've debugged this by modifying another property in the model and that saves fine.

So I really am at a loss as to why this is not saving. If anyone has any ideas as to why its not saving that would be life saver material:

The Model:

public class Page
{
    public int Id { get; set; }
    public string PageURL { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public List<DateTime> Visits { get; set; }

    public Page()
    {
      Visits = new List<DateTime>();
    }

}

Here's my code:

private ApplicationDbContext db = new ApplicationDbContext();

   public ActionResult CookiePolicy()
   {
        var page = db.Pages.FirstOrDefault(c => c.PageURL == "cookiepolicy");

        page.Visits.Add(DateTime.Now); // this list of datetime objects does not get updated
        page.Title = "test "; //but this property does
        ViewBag.Title = page.Title;

        db.Entry(page).State = EntityState.Modified;
        db.SaveChanges();

        return View(page);
    }
like image 391
Jay Avatar asked Nov 09 '22 23:11

Jay


1 Answers

Edit Fabio Luz mentioned:

"collection of primitive types (like int, DateTime, bool) are not supported"

So the solution below seems like the right option.

Ok, so after some deliberation. I decided to create a new model called vist and have this as the list instead of datetime:

public class Visit
{
    public int Id { get; set; }
    public DateTime DateTime { get; set; }
    public BrowserType BrowserType { get; set; }
    public String Duration { get; set; }

    public int PageId { get; set; }
    public virtual Page Page { get; set; }

    public Visit()
    {
        DateTime = DateTime.Now;
        BrowserType = BrowserType.Other;
    }
}

There are benefits to this. Now I can store more information then just the datetime.

So for anyone who had the same problem as me. Consider pushing it out into its own model for greater flexibility.

like image 63
Jay Avatar answered Nov 14 '22 23:11

Jay