Datetime MVC data list not save

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

However, when I do EntityState.Modified , the changes are not saved. I debugged this by changing another property in the model and keeping everything in order.

Therefore, I really do not understand why this does not save. If anyone has ideas on why this is not a salvation, it will be a salvage material:

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 is 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); } 
+5
source share
2 answers

Like Fabio Luz mentioned in his comment, primitive type collections are not supported. It is generally assumed that a collection in a class derived from context is a one-to-many / many-to-many relationship.

When building models, remember how they will be presented in the SQL table, and the presence of a column that has a collection inside is not supported in such a structure. Now, if you were referring to a different object (table) than the object (record in the table) would have certain properties, such as a primary key, etc.

Hope this helps.

Edit:

Here is an example of a model that you might want to consider:

 public class Page { public int Id { get; set; } public string PageURL { get; set; } public string Name { get; set; } public string Title { get; set; } public virtual IQueriable<Visit> Visits { get; set; } } public class Visit { // ... properties related to data you wish to retain about the visit public virtual Page Page { get; set; } // navigation property } 
0
source

Edit Fabio Luz mentioned:

"a collection of primitive types (e.g. int, DateTime, bool) is not supported"

So, the solution below seems to be the right option.

So, after some discussion. I decided to create a new model called vist and have this as a 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 advantages to this. Now I can store more information and then just datetime.

So, for those who had the same problem as me. Consider introducing it into your model for more flexibility.

+1
source

Source: https://habr.com/ru/post/1238505/


All Articles