I am learning ASP.NET Core MVC and my model is
namespace Joukyuu.Models
{
public class Passage
{
public int PassageId { get; set; }
publi
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?
Solution 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!
Solution 2)
Custom attribute:
[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDate { get; set; }
Entity Framework 6 Code first Default value
Solution 3)
with help of Computed:
[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/
Solution 4) You can also do this with command interceptor by modifying manually the query.
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
Solution 6) just set it or get in in the UI or in your VM.
In Entity Framework Core 1.0 easy:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.Property(b => b.CreatedDate )
.HasDefaultValueSql("getdate()");
}