justiceorjustus justiceorjustus - 1 year ago 91
SQL Question

MVC / EF DB First and SQL Constraint Default TimeStamp field

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:


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:

public ActionResult Create([Bind(Include = "ChainId,Name")] Chain chain)
if (ModelState.IsValid)
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" })

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?

Answer Source

My guess is your are getting NULL from the view and inserting NULL but your field say NOT NULL

Instead of just ommit the parameter from the EF Insert query. So the default take over.

  INSERT INTO yourTable (field1, yourDate) VALUES ('something', NULL);
  INSERT INTO yourTable (field1) VALUES ('something');  

You can always set the field on your EF side;

  Model.TimeStamp = DateTime.Now;


([Bind(Include = "ChainId,Name")] Chain chain)

When you use the Include you are saying, from the object I get from the FORM take only ChainId,Name the rest of the properties will be NULL

That is why you get an error for trying to insert NULL


Check this video tutorial and maybe you understand it better.

If you build your own SqlQuery Object, then you can specify your parameter and omit the Timestamp field. In that case the DEFAULT will apply

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download