我有一个简单的 MVC4 模型,它添加了一个 DateTime.Now
到 List<DateTime>()
列表。
然而,当我执行 EntityState.Modified
时, 更改不会被保留。
我已经通过修改模型中的另一个属性对此进行了调试,并且可以很好地保存。
所以我真的很困惑为什么这不是节省。如果有人对为什么不保存有任何想法,那将是救命稻草:
模型:
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>();
}
}
这是我的代码:
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);
}
最佳答案
Edit Fabio Luz mentioned:
"collection of primitive types (like int, DateTime, bool) are not supported"
So the solution below seems like the right option.
好的,经过深思熟虑。我决定创建一个名为 vist 的新模型,并将其作为列表而不是日期时间:
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;
}
}
这样做有好处。现在我可以存储更多信息,然后只存储日期时间。
对于和我有同样问题的人来说。考虑将其推出自己的模型以获得更大的灵 active 。
关于c# - MVC 日期时间列表未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34331024/