日期时间列和实体框架 [英] Datetime column and entity framework

查看:52
本文介绍了日期时间列和实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据模型(实体框架6.1.3,ASP.NET MVC 5,具有现有数据库的Code First,SQL Server 2016)包含标题表,其中包含 ModifiedDate datetime ,DEFAULT(getdate))列。



在浏览器中创建新记录时,要求用户键入ModifiedDate值而不是SQL Server自动应用它们。我尝试了一些我能想到的技巧(我甚至在表中创建了一个AFTER UPDATE触发器来设置日期),但没有成功。从模型中删除ModifiedDate列并创建新的控制器和视图后,SQL Server将应用这些值,但我再也看不到这些值了。



重新插入ModifiedDate列和[DatabaseGenerated(DatabaseGeneratedOption.Computed)]属性的应用我然后能够创建一个新记录,但是当编辑现有记录时,不会生成ModifiedDate的新值,只会应用ModifiedDate文本框中显示的值(这是创建记录的日期)。我想知道处理这种情况的方法。我只是希望服务器应用ModifiedDate值并能够看到这个值。



这是型号代码:





My data model (Entity Framework 6.1.3, ASP.NET MVC 5, Code First with an existing database, SQL Server 2016) includes a "Title" table with a "ModifiedDate" (datetime, DEFAULT (getdate)) column.

On creating a new record in browser the user is asked to type the ModifiedDate value instead of SQL Server applying them automatically. I tried a few tricks I could think of (I even created an AFTER UPDATE trigger in the table to set the date) but without success. After removing ModifiedDate column from the model and creating new controller and views the values are applied by SQL Server but I cannot longer see the values anymore.

By reinserting the ModifiedDate column and application of the [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attribute I’m then able to create a new record but when editing an existing record a new value for ModifiedDate is not generated and only the value that shows in the ModifiedDate textbox is applied (that is the date the record has been created). I wonder about the way to handle this situation. I just wish the server to apply the ModifiedDate value and being able to see this value.

Here’s the models code:


[Table("Title")]
public partial class Title
{
    public int TitleID { get; set; }

    [Required]
    [StringLength(50)]
    public string Title { get; set; }

    public DateTime ModifiedDate { get; set; }
}





在此先感谢Corbex。



我尝试过:



我试过这个模型:



Thanks in advance, Corbex.

What I have tried:

I have tried this model instead:

[Table("Title")]
public partial class Title
{
    public int TitleID { get; set; }

    [Required]
    [StringLength(50)]
    public string Title { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime ModifiedDate { get; set; }
}

推荐答案

试试这个解决方案



EF6:使用代码优先迁移自动添加创建的日期/时间列 [ ^ ]
Try this solution

EF6: Adding a Created Date/Time Column Automatically with Code First Migrations[^]


这篇关于日期时间列和实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆