【发布时间】:2018-01-07 20:12:55
【问题描述】:
我的User 模型中有CreatedAt 和UpdatedAt 列。
User.cs
public string Name { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
要求
- 当我们
SaveChanges()用户记录时,CreatedAt和UpdatedAt应该自动保存例如:DateTime.UtcNow - 当我更新
User记录时,只有UpdatedAt列应该更新为当前日期时间。 - 对于所有其他型号,这应该会自动发生,可能是
OnModelCreating()中的某些配置。 - 我希望这种行为能够从数据库和其他地方找到
latest记录。 - 我正在使用
code first迁移方法 - 我正在使用 MySQL 服务器,
MySql.Data,MySql.Data.Entity.EF6。
更新
我添加了BaseEntity.cs模型
public abstract class BaseEntity
{
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
从 BaseEntity 继承用户
public class User : BaseEntity
{
public int Id { get; set; }
public int FullName { get; set; }
}
并更新了迁移以包括 defaultValueSql()
AddColumn("dbo.Users", "CreatedAt", c => c.DateTime(nullable: false, precision: 0, defaultValueSql: "NOW()"));
AddColumn("dbo.Users", "UpdatedAt", c => c.DateTime(nullable: false, precision: 0, defaultValueSql: "NOW()"));"
现在,需要一种方法来修复每次更新中的 UpdatedAt 列。
【问题讨论】:
-
先用数据库,再用sql实现?
-
不,我先使用代码。我找到了
AddColumn("dbo.Users", "CreatedAt", c => c.DateTime(nullable: false, precision: 0, defaultValueSql: "UTC_TIMESTAMP()"));但update-migration给出了语法错误。 -
但在 mysql 查询中运行
select UTC_TIMESTAMP();会给出当前日期时间戳 -
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UTC_TIMESTAMP()' at line 1
标签: c# asp.net-mvc-5 entity-framework-6