c# - MVC 日期时间列表未保存

标签 c# entity-framework asp.net-mvc-4

我有一个简单的 MVC4 模型,它添加了一个 DateTime.NowList<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/

相关文章:

c# - 使用 EF6 从数据库中选择大量数据异步

C# SQL/Linq/Entity Framework 计算来自大数据源的多列的列总计

c# - ASP.net MVC - Razor HTML Helper 正在占用内存而不放手

Javascript 代码片段无法在 Chrome 中运行,但可以在 Internet Explorer 中运行

javascript - 使用 Jquery/Javascript 读取 NewtonSoft Json 数据

c# - 如何从 VB.NET 中的事件中获取实际的 EventHandler 委托(delegate)实例?

c# - 我可以在 C# 中访问对象的字段吗

c# - ConfigurationManager.ConnectionStrings 从 machine.config 返回额外的连接字符串

c# - 需要简单的 linq

mysql - 无法在 Visual Studio 中使用 mysql.data.entity.EF6 为 MySql 数据库创建 .edmx