0

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?

justiceorjustus
  • 2,017
  • 1
  • 19
  • 42
  • 1
    Show us what are you doing now? Please read [**How-to-Ask**](http://stackoverflow.com/help/how-to-ask) And here is a great place to [**START**](http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/) to learn how improve your question quality and get better answers. – Juan Carlos Oropeza Aug 19 '16 at 13:48
  • check your variable `chain` what value have on TimeStamp? – Juan Carlos Oropeza Aug 19 '16 at 13:55

1 Answers1

1

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);
  vs
  INSERT INTO yourTable (field1) VALUES ('something');  

You can always set the field on your EF side;

  Model.TimeStamp = DateTime.Now;

EDIT:

([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

 db.Chains.Add(chain);
 db.SaveChanges();

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

Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
  • Thank you, setting the model.TimeStamp = DateTime.Now did the trick. I'm not sure if it's proper on my end considering the auto-generated field still exists, but it achieves the same end. – justiceorjustus Aug 19 '16 at 13:59
  • Thanks for the info! This is only my 2nd MVC project and I love kudvenkat's videos! I feel like my issue is that it's a required NOT NULL field in my database, so it freaks out when I try to include it in the bind but also hide it on the form. Am I correct? – justiceorjustus Aug 19 '16 at 14:06
  • Not sure what is happening. But you can try to see what is the [Sql Query](http://stackoverflow.com/questions/1412863/how-do-i-view-the-sql-generated-by-the-entity-framework) been sent to DB. Will have to test it but I belive the EF try to insert every field, so doesnt implement default values. That is why I mention you could create your own SqlQuery. – Juan Carlos Oropeza Aug 19 '16 at 14:12
  • Yes, looks like is a recurring problem. http://stackoverflow.com/questions/1609304/how-to-use-the-default-entity-framework-and-default-date-values – Juan Carlos Oropeza Aug 19 '16 at 14:12