我正在学习 ASP.NET Core MVC,我的模型是
I am learning ASP.NET Core MVC and my model is
namespace Joukyuu.Models
{
public class Passage
{
public int PassageId { get; set; }
public string Contents { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
}
Passage
表是用来保存我写的段落的.
The Passage
table is used to save passages I wrote.
Create
视图只有一个字段Contents
用于输入段落.CreatedDate
和 ModifiedDate
必须由服务器自动设置为相等(使用 UTC 格式).
Create
view just has one field Contents
to input a passage. CreatedDate
and ModifiedDate
must be automatically set equal by the server (using UTC format).
Edit
视图只有一个字段Contents
来编辑段落.ModifiedDate
必须由服务器自动设置.
Edit
view just has one field Contents
to edit a passage. ModifiedDate
must be automatically set by the server.
我必须将哪些属性附加到 CreatedDate
和 ModifiedDate
属性以使服务器根据上述情况自动填充它们?
What attributes I have to attach to the CreatedDate
and ModifiedDate
properties to make them automatically populated by the server based on the above scenario?
我必须将哪些属性附加到 CreatedDate 和 ModifiedDate 属性以使服务器根据上述情况自动填充它们?
What attributes I have to attach to the CreatedDate and ModifiedDate properties to make them automatically populated by the server based on the above scenario?
解决方案 1)
namespace Joukyuu.Models
{
public class Passage
{
public int PassageId { get; set; }
public string Contents { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public Passage()
{
this.CreatedDate = DateTime.UtcNow;
this.ModifiedDate = DateTime.UtcNow;
}
}
}
通过编辑,您必须自己更改/更新它!
and by edit you have to change/update it by your self!
解决方案 2)
自定义属性:
[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDate { get; set; }
实体框架6代码优先默认值
解决方案 3)
在计算的帮助下:
[Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreatedUtc { get; set;
"dbo.Products",
c => new
{
ProductId = c.Int(nullable: false, identity: true),
Name = c.String(),
CreatedUtc = c.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()"),
})
.PrimaryKey(t => t.ProductId);
https://andy.mehalick.com/2014/02/06/ef6-adding-a-created-datetime-column-automatically-with-code-first-migrations/
解决方案 4)您也可以通过手动修改查询来使用命令拦截器来做到这一点.
Solution 4) You can also do this with command interceptor by modifying manually the query.
解决方案 5)使用 Repository 模式管理数据创建并由 CreateNew 设置这是我喜欢的解决方案!
Solution 5) Use Repository pattern to manage the data creation and set it by CreateNew This is my favour Solution!
https://msdn.microsoft.com/en-us/library/ff649690.aspx
解决方案 6)只需在 UI 或 VM 中设置或进入.
Solution 6) just set it or get in in the UI or in your VM.
在Entity Framework Core 1.0中很容易:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Passage>()
.Property(b => b.CreatedDate )
.HasDefaultValueSql("getdate()");
}
这篇关于如何自动填充 CreatedDate 和 ModifiedDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!