My model has a TimeStamp column which is auto generated when the record is created. I'm using the default CRUD scaffolding with Razor Syntax. At this point I'm just getting started with the project so it is the basic generated controllers and views from Visual Studio using entity framework.
The column is set as this in the database:
TimeStamp DATETIME NOT NULL CONSTRAINT [DF_Chains_TS] DEFAULT (GETDATE())
This is the generated model:
public partial class Chain
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public int ChainId { get; set; }
public string Name { get; set; }
public System.DateTime TimeStamp { get; set; }
}
This is the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ChainId,Name")] Chain chain)
{
if (ModelState.IsValid)
{
db.Chains.Add(chain);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(chain);
}
I am trying this in the view:
<div class="form-group">
@*Html.LabelFor(model => model.TimeStamp, htmlAttributes: new { @class = "control-label col-md-2" })*@
<div class="col-md-10">
@Html.HiddenFor(model => model.TimeStamp, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.TimeStamp, "", new { @class = "text-danger" })
</div>
</div>
When attempting to create a new record in the Create View I'm either getting that the field is required or it is writing null to the TimeStamp field. I think my issue is I'm not sure how to handle auto-generated fields in the controller or view. Can anyone help with how to write a record with such a field or if I need to add any specific Data Annotations?